我正在尝试使用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标头已经存在'错误。这必须意味着HttpClient已经发送了Content-Length。 Unfortunatley我无法访问服务器端。任何想法为什么会返回这些错误?
答案 0 :(得分:2)
试试这个,
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost("https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/tokenservice");
request.setHeader("Content-type", "application/json");
request.setHeader("Accept", "application/json");
request.addHeader("Authorization", "Basic " + Base64.encodeToString((appId + ":" + appSecret).getBytes(), Base64.DEFAULT));
JSONObject obj = new JSONObject();
obj.put("grant_type", "authorization_code");
obj.put("code", code);
obj.put("scope", "https://uri.paypal.com/services/paypalhere");
request.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = httpClient.execute(request);