在android上使用httpclient时发布体空

时间:2012-06-29 06:06:33

标签: android post httpclient urlconnection

上下文:在Android中,当我使用Java的HttpURLConnection对象时,如下所示,我在服务器端正确看到了POST正文。但是,当我使用我认为是等效的HttpClient代码时,POST主体是空的。

问题

  1. 我错过了什么?

  2. 服务器端是一个Django-python服务器。我在此端点的入口点设置了一个调试点,但是帖体已经是空的。我如何调试它以找出为什么主体为空?

  3. 注意:我已经查看了this,但该解决方案对我不起作用。

    代码:使用HttpURLConnection - 这有效:

    try {
        URL url = new URL("http://10.0.2.2:8000/accounts/signup/"); 
        String charset = "UTF-8";
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty  ("Authorization", "Basic base64encodedstring==");
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type", 
            "application/x-www-form-urlencoded; charset=" + charset);
        connection.setDoInput(true);
    
        StringBuilder sb =  new StringBuilder();
        sb.append("appver=6&user=value1pw=&hash=h1");
    
        OutputStreamWriter outputWriter = new 
            OutputStreamWriter(connection.getOutputStream());
        outputWriter.write(sb.toString());
        outputWriter.flush();
        outputWriter.close();
        // handle response
    } catch () { 
        // handle this 
    }
    

    =============================================== =============

    代码:使用Apache httpclient - 不起作用 - 服务器获取空POST主体:

        HttpPost mHttpPost = new HttpPost(""http://10.0.2.2:8000/accounts/signup/"");
        mHttpPost.addHeader("Authorization", "Basic base64encodedstring==");
        mHttpPost.addHeader("Content-Type", 
            "application/x-www-form-urlencoded;charset=UTF-8");
        mHttpPost.addHeader("Accept-Charset", "UTF-8");
    
        String str = "appver=6&user=value1pw=&hash=h1"; // same as the above
        StringEntity strEntity = new StringEntity(str);
        mHttpPost.setEntity(strEntity);
    
        HttpUriRequest pHttpUriRequest = mHttpPost; 
    
        DefaultHttpClient client = new DefaultHttpClient();
        httpResponse = client.execute(pHttpUriRequest);
        // more code
    

1 个答案:

答案 0 :(得分:1)

我想到了这种情况发生的原因:

POST请求中的授权标头有一个额外的新行字符“\ n” - 这导致请求进入服务器端处理程序,但是正文被切断。我之前从未注意过这种行为。