Michael Ramos
Michael Ramos

Reputation: 5817

Why does QueryParam return null

I hava a post method where I try and add the parameter "enc":

protected void sendPost(String url, String encData) throws Exception {

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    //add request header
    con.setRequestMethod("POST");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    // Send post request
    con.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
    wr.write("enc="+encData);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    //System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);
}

However in my server code (below) I get a value of NULL when trying to get the data. Its just a string, not JSON or anything fancy. I've also tried writing the param as "?enc="+endData, and that does not work either. Also the path encRead is entered in the url, so I don't think that is the issue.

    @Path("/encRead")
    @POST
    public void decryptData(@QueryParam("enc") String enc) {

        System.out.println("got endData: "+enc);

    }

So far I've been referencing the answers from Jersey POST Method is receiving null values as parameters but still come up with no solution

Upvotes: 1

Views: 1546

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208974

The problem is you are trying to write to the body of the request, with wr.write("enc="+encData);. @QueryParams should be in the query string. So this instead would work

public static void main(String[] args) throws Exception {
    sendPost(".../encRead", "HelloWorld");
}

protected static void sendPost(String url, String encData) throws Exception {
    String concatUrl = url + "?enc=" + encData;
    URL obj = new URL(concatUrl);
    [...]
    //wr.write("enc=" + encData);

Upvotes: 1

Related Questions