gpt4 book ai didi

java - 在 android 上具有授权的 HTTP POST 请求

转载 作者:IT老高 更新时间:2023-10-28 23:26:51 26 4
gpt4 key购买 nike

当我使用 HttpPost 的 setHeader 设置“授权” header 时,主机名从请求中消失,并且总是返回错误 400(错误请求)。相同的代码在纯 java(没有 android)上运行良好,当我在 android 上删除设置“授权” header 时它运行良好,但我需要授权。这是一个代码(域已更改):

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 编码的“登录:密码”,例如:“YnxpcYRlc3RwMTulHGhlSGs=”,但这并不重要。

这是在纯 java 上调用上述代码时的一段 lighttpd 的 error.log:

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

并从 access.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

access.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 时没有区别。

最佳答案

感谢 Samuh 的提示 :)插入了一个额外的换行符,这在 GET 请求中没有意义,但在 POST 请求中很重要。这是在 android 中生成 Authorization header 的正确方法(在本例中为 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 标志。

关于java - 在 android 上具有授权的 HTTP POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5092561/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com