How to customize HttpPost headers for client request in Java Android

I'm having trouble getting the Apache HttpClient to send the HttpPost header correctly.

I have no problem sending name value pairs and whatever, but whenever I set or add the POST header, it disappears when the request is made.

I tried both setHeader and addHeader and also try both at once.

Here is my code:

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("https://posttestserver.com/post.php");
    httppost.setHeader("Authorization: Bearer", accessToken);
    httppost.addHeader("Authorization: Bearer", accessToken);
    Log.d("DEBUG", "HEADERS: " + httppost.getFirstHeader("Authorization: Bearer"));

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = httpclient.execute(httppost, responseHandler);

    Log.d("DEBUG", "RESPONSE: " + responseBody);

      

Also, the debug command prints out the correct header before executing the request, so I know it is being added and then just discarded later.

Any help would be greatly appreciated!

EDIT: This all works inside AsyncTask, if that matters. I don't think this is happening because there is a NetworkOnMainThread exception, otherwise, but I thought it was worth mentioning.

+3


source to share


5 answers


Try connecting a service that tells your HTTP headers and prints (just prints simple HTML) output. At the very least, you'll know if your headers are really lost along the way, or maybe something else.



+2


source


At least one error in the code. Try this instead:



httppost.setHeader("Authorization", "Bearer "+accessToken);

      

+19


source


You said that the header does not respond to the response in one of your responses, just to clarify, the headers are not returned in the response, they are simply sent on request to the server. A network trace or a fiddler session can display a request and a response, and that should give you a definitive answer as to whether they are discarded or not.

+1


source


try using java.net.URLConnection.addRequestProperty(String field, String newValue)

http://developer.android.com/reference/java/net/URLConnection.html#addRequestProperty%28java.lang.String,%20java.lang.String%29

0


source


Personally, I prefer to use a different method to properly configure http authorization:

httpClient.getCredentialsProvider().setCredentials(
  new AuthScope(hostname, port), 
  new UsernamePasswordCredentials(user, pass));

      

-1


source







All Articles