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

别说谁变了你拦得住时间么 提交于 2019-12-07 12:19:46

问题


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.


回答1:


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.




回答2:


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

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



回答3:


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.




回答4:


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




回答5:


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

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


来源:https://stackoverflow.com/questions/14655062/how-to-set-httppost-headers-for-a-client-request-in-java-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!