[英]Android java http with authentication remove Content-Type
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: 最近,我正在使用HTTPPost处理请求,并且我需要使用Content-Type设置标头:application / json,它需要基本的身份验证,这可能是这样的:
A: 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: 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 使用方法A,将仅保留身份验证的请求标头,是的,“ Content-type”消失了
Only B works perfectly. 只有B可以完美工作。
Has any one meet similar issue before? 有人遇到过类似的问题吗? Please please help me out, thanks :) 请帮帮我,谢谢:)
Which version of httpclient
are you using ?Can you upgrade to the latest and try again.Looks like a bug to me. 您使用的是哪种版本的httpclient
?可以升级到最新版本,然后重试。
The java doc says : Java文档说:
void addHeader(String name, String value) Adds a header to this message. void addHeader(String name,String value)向此消息添加标头。 The header will be appended to the end of the list. 标头将添加到列表的末尾。
Finally, I found my mistake in solution A: 最后,我在解决方案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. 显然,当使用Base64编码authenticationToken时,我设置了Base64.Default,密钥在这里,我们不应该这样做,我们应该将其设置为Base64.NO_WRAP。
Ref: http://developer.android.com/reference/android/util/Base64.html 参考: http : //developer.android.com/reference/android/util/Base64.html
Ref: http://blog.moes.as/2012/05/basic-http-authentication.html 参考: http : //blog.moes.as/2012/05/basic-http-authentication.html
Thank god.... didn't understand this at all. 谢谢上帝...一点都不明白。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.