1

Recently I am working on a request with HTTPPost, and I need to set header with Content-Type: application/json, and it requires basic authentication, Here is may way:

A:

httpPost.setHeader("Content-type","application/json");
String authenData = String.format(Locale.getDefault(), "%s:%s", "xxx@xxx.com", "xxx");
String base64EncodedCredentials = Base64.encodeToString(authenData.getBytes(), Base64.DEFAULT);
httpPost.addHeader("Authentication", "Basic " + base64EncodedCredentials);

B:

httpPost.setHeader("Content-type","application/json");
httpPost.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials("xxx@xxxx.com", "xxxx"), "UTF-8", false));

And, Guess what? With method A, the request header will be only Authentication left, yes, "Content-type" is gone

Only B works perfectly.

Has any one meet similar issue before? Please please help me out, thanks :)

David_Wang
  • 652
  • 9
  • 20

2 Answers2

0

Which version of httpclient are you using ?Can you upgrade to the latest and try again.Looks like a bug to me.

The java doc says :

void addHeader(String name, String value) Adds a header to this message. The header will be appended to the end of the list.

abhati
  • 309
  • 1
  • 6
  • I am developing Android Project, and have no idea which httpclient version it is. Found something in here: http://stackoverflow.com/questions/2618573/what-version-of-apache-http-client-is-bundled-in-android-1-6/4818714#4818714 – David_Wang Dec 17 '14 at 02:14
  • @adhati, check my answers, I just figure it out. – David_Wang Dec 17 '14 at 02:40
0

Finally, I found my mistake in solution A:

Apparently, when use Base64 to encode the authenticationToken, I set Base64.Default, the key is here, we should not do that, we should set it as Base64.NO_WRAP.

Ref: http://developer.android.com/reference/android/util/Base64.html

Ref: http://blog.moes.as/2012/05/basic-http-authentication.html

Thank god.... didn't understand this at all.

David_Wang
  • 652
  • 9
  • 20