在安卓上具有授权的 HTTP POST 请求

2022-09-02 22:57:57

当我从HttpPost使用setHeader设置“授权”标头时,主机名从请求中消失,并且始终返回错误400(错误请求)。相同的代码在纯java(没有Android)上工作正常,当我删除Android上的设置“Authorization”标头时,它可以正常工作,但我需要授权。这是一个代码(域已更改):

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://myhost.com/test.php");
post.setHeader("Accept", "application/json");
post.setHeader("User-Agent", "Apache-HttpClient/4.1 (java 1.5)");
post.setHeader("Host", "myhost.com");
post.setHeader("Authorization",getB64Auth());
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("data[body]", "test"));
AbstractHttpEntity ent=new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
ent.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
ent.setContentEncoding("UTF-8");
post.setEntity(ent);
post.setURI(new URI("http://myhost.com/test.php"));
HttpResponse response =client.execute(post);

方法getB64Auth()返回使用Base64编码的“login:password”,例如:“YnxpcYRlc3RwMTulHGhlSGs=”,但这并不重要。

这是 lighttpd 的一个错误.log当在纯 java 上调用上述代码时:

2011-02-23 15:37:36: (request.c.304) fd: 8 request-len: 308
POST /test.php HTTP/1.1
Accept: application/json
User-Agent: Apache-HttpClient/4.1 (java 1.5)
Host: myhost.com
Authorization: Basic YnxpcYRlc3RwMTulHGhlSGs=
Content-Length: 21
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Encoding: UTF-8
Connection: Keep-Alive

HTTP/1.1 200 OK
Content-type: text/html
Transfer-Encoding: chunked

和从访问记录.log(IP 已更改):

1.1.1.1 myhost.com - [23/Feb/2011:15:37:36 +0100] "POST /test.php HTTP/1.1" 200 32 "-" "Apache-HttpClient/4.1 (java 1.5)"

当在android上调用相同的代码时,我在日志中得到这个:

POST /test.php HTTP/1.1
Accept: application/json
User-Agent: Apache-HttpClient/4.1 (java 1.5)
Host: myhost.com
Authorization: Basic YnxpcYRlc3RwMTulHGhlSGs=

Content-Length: 21
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Encoding: UTF-8
Connection: Keep-Alive
Expect: 100-Continue


2011-02-23 15:45:10: (response.c.128) Response-Header:
HTTP/1.1 400 Bad Request
Content-Type: text/html
Content-Length: 349
Connection: close

访问.log:

1.1.1.1 - - [23/Feb/2011:15:45:10 +0100] "POST /test.php HTTP/1.1" 400 349 "-" "Apache-HttpClient/4.1 (java 1.5)"

如何在Android上使用POST获得授权?当我使用HttpURLConnection而不是HttpClient时,这没有什么区别。


答案 1

感谢Samuh的提示:)插入了一个额外的换行符,在GET请求中没有意义,但在POST请求中很重要。这是在android中生成授权标头的正确方法(在本例中为getB64Auth):

 private String getB64Auth (String login, String pass) {
   String source=login+":"+pass;
   String ret="Basic "+Base64.encodeToString(source.getBytes(),Base64.URL_SAFE|Base64.NO_WRAP);
   return ret;
 }

缺少Base64.NO_WRAP旗。


答案 2

简单地使用这个:

String authorizationString = "Basic " + Base64.encodeToString(
                        ("your_login" + ":" + "your_password").getBytes(),
                        Base64.NO_WRAP); //Base64.NO_WRAP flag
                post.setHeader("Authorization", authorizationString);

推荐