简体   繁体   中英

How to Set HttpPost Headers for a Client Request in Java Android

I am having trouble getting the Apache HttpClient to correctly send an HttpPost Header.

I have no problems sending name value pairs and whatnot, but whenever I set or add a POST Header, it disappears when the request is made.

I have tried both setHeader and addHeader, as well as trying 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);

Additionally, the debug statement before the request is executed prints out the correct header, so I know it is being added, then just dropped later.

Any help would be much appreciated!

EDIT: This is all running inside of an AsyncTask if that matters. I don't think it does since there is a NetworkOnMainThread exception thrown otherwise but I thought it might be worth mentioning.

At least one mistake in your code. Try this instead:

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

Try to connect the service that tells your HTTP headers and capture (just print plain HTML) the output. At least you will know if your headers are really lost on the way or maybe something else.

You said the header is not on the response in one of your replies, just to clarify, headers don't come back on the response, they are just sent on the request to the server. A network trace or fiddler session can show the request and response, and this should give you a definitive answer of whether they are getting dropped or not.

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

Personally i prefer use an other methos to set properly the http authorization:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM