4

我正在尝试使用 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。不幸的是,我无法访问服务器端。任何想法为什么会返回这些错误?

4

1 回答 1

3

尝试这个,

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);
于 2013-03-21T16:13:23.637 回答