Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpURLConnection conn.getRequestProperty return null

I'm trying to push some data to an URL (MDS_CS) for a BES

when i set some Request Headers in my code, and submit the request, the submited request's header is set to null.

here is my code :

        HttpURLConnection conn =(HttpURLConnection)url.openConnection();
        conn.setDoInput(true);//For receiving the confirmation
        conn.setDoOutput(true);//For sending the data
        conn.setRequestMethod("POST");//Post the data to the proxy
        conn.setRequestProperty("X-Rim-Push-ID", pushId);
        conn.setRequestProperty("Content-Type", "text/html");
        conn.setRequestProperty("X-Rim-Push-Title", "-message");
        conn.setRequestProperty("X-Rim-Push-Type", "browser-message");                 
        conn.setRequestProperty("X-Rim-Push-Dest-Port", "7874");            
        //Write the data
        OutputStream out = conn.getOutputStream();
        out.write(data.getBytes());
        out.close();

        System.out.println(conn.getHeaderField("X-Rim-Push-ID"));

the last line return null when i try to retrieve the X-Rim-Push-Title it is NULL only X-Rim-Push-ID which is correctly retrieved,

please help me

like image 957
dzgeek Avatar asked Jul 18 '12 14:07

dzgeek


2 Answers

Not quite sure what you really want to do. But to see what is posted to the server you would have to post it to your own and read the data you receive there.

If you want to see all the REQUEST headers you could:

for (String header : conn.getRequestProperties().keySet()) {
   if (header != null) {
     for (String value : conn.getRequestProperties().get(header)) {
        System.out.println(header + ":" + value);
      }
   }
}

Or after connecting you can print out the RESPONSE headers:

for (String header : conn.getHeaderFields().keySet()) {
   if (header != null) {
     for (String value : conn.getHeaderFields().get(header)) {
        System.out.println(header + ":" + value);
      }
   }
}
like image 128
morja Avatar answered Sep 18 '22 02:09

morja


I would suggest using Apache HttpClient

final HttpClient client = new HttpClient();
final PostMethod method = new PostMethod(uri);
method.addRequestHeader("X-Rim-Push-Title", "-message");
client.executeMethod(method);
String responseBody = method.getResponseBodyAsString();
Header[] headers = method.getResponseHeaders();

HttpClient is a much more powerful way of dealing with HTTP than HttpURLConnection.

like image 39
Kieran Avatar answered Sep 22 '22 02:09

Kieran