【发布时间】:2013-03-21 15:55:03
【问题描述】:
我正在尝试使用 Android Apache HttpClient 进行 POST,但它返回错误 411 Content-Length Required。这是代码。
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost("https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/tokenservice");
request.addHeader("Authorization","Basic "+ Base64.encodeToString((appId+":"+ appSecret).getBytes(),Base64.DEFAULT));
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
postParameters.add(new BasicNameValuePair("code", code));
postParameters.add(new BasicNameValuePair("scope", "https://uri.paypal.com/services/paypalhere"));
UrlEncodedFormEntity entity;
entity = new UrlEncodedFormEntity(postParameters);
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
Log.d("HTTPStatus",response.getStatusLine().toString());
InputStream bufferedReader =
response.getEntity().getContent();
StringBuffer stringBuffer = new StringBuffer("");
byte[] line = new byte[1024];
while (bufferedReader.read(line) > 0) {
stringBuffer.append(new String(line));
}
bufferedReader.close();
Log.d("str",stringBuffer.toString());
我已尝试添加该行:-
request.addHeader("Content-Length",Long.toString(entity.getContentLength()));
但后来我得到一个“org.apache.http.ProtocolException: Content-Length header already present”错误。这一定意味着 HttpClient 已经在发送 Content-Length。不幸的是,我无法访问服务器端。任何想法为什么会返回这些错误?
【问题讨论】:
-
您是否尝试过使用 HTTP 而不是 HTTPS 将其发布到运行 Wireshark 的 PC 以查看生成的确切内容?另外,您使用的是什么版本的 Android HTTP 客户端?
-
我将它发送到一个 HTTP 地址并运行了 wireshark。它不是作为 Wireshark 中的帖子出现,而是作为 [重新组装的 PDU 的 TCP 段],不知道这意味着什么。这是捕获数据包。
-
TRSNIFF 数据 uB ô ÿk= æ !·,+$w72l E ØGQ@ @?ãÀ¨ ÂCyÈ P—rX³Á7 -Ph„ POST ************ HTTP/ 1.1 Content-Type: application/xml;charset=UTF-8 Authorization: Basic *************** Content-Length: 103 Host: *********** ** 连接:保持活动用户代理:Apache-HttpClient/UNAVAILABLE (java 1.4) {"grant_type":"authorization_code","scope":"https:\/\/uri.paypal.com\/services\/ paypalhere","code":"*************"}
-
请参考这里的答案,看来你也有同样的问题stackoverflow.com/questions/6857796/…
标签: android post httpclient