Search code examples
javahttpsurlconnection

httpsurlconnection not setting headers on addRequestProperty


I have been stuck in a bit of a pickle - when running a httpsurlconnection call I am trying to set a series of headers however when debugging it is showing the headers I have added as NULL.

Code:

    URL obj = new URL(url);

    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(proxy);

    //HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    con.setDoInput(true);
    con.setDoOutput(true);

    //add reuqest header
    con.setRequestMethod("POST");
    con.addRequestProperty("Accept-Language", "en-GB");
    con.addRequestProperty("X-ApiKey", "xxxx-xxx-xxx-xxx-xxx");
    con.addRequestProperty("Content-Type", "application/json");


    List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair("Password", "xxxxxxxxxxxxxx"));
    postParameters.add(new BasicNameValuePair("Email", "[email protected]"));

    OutputStream os = con.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os));
    writer.write(getQuery(postParameters));
    writer.flush();
    writer.close();
    os.close();

To test they are being correctly set I have added

con.getHeaderField("X-ApiKey");
con.getHeaderFields();

to determine whether my Header fields have been correctly set. However it appears they have not.

Responses accordingly:

Post Headers: null

Post Headers: {Content-Length=[11339], Connection=[keep-alive], X-Frame-Options= [SAMEORIGIN], X-Request-Identifier=[xxxxxxxxxxxxxxxxxx], Date=[Wed, 05 Oct 2016 16:56:49 GMT], Content-Type=[text/html], null=[HTTP/1.1 400 Bad Request], Cache-Control=[private]}

Where am I going wrong in the above code which is not setting the headers correctly.


Solution

  • You should use con.getRequestProperty("X-ApiKey") and con.getRequestProperties()

    The method getHeaderField("") returns the value of the header field from the response header. It is very confusing, so it should be better called getResponseHeaderField("name")

    The output is not empty because your connection got already a response from the server after openConnection(URL) get called.