【问题标题】:post body empty when using httpclient on android在android上使用httpclient时发布正文为空
【发布时间】:2012-06-29 06:06:32
【问题描述】:

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

问题

  1. 我错过了什么?

  2. 服务器端是 Django-python 服务器。我已经在这个端点的入口点设置了一个调试点,但是帖子正文已经是空的。如何通过它进行调试以找出正文为空的原因?

注意:我已经看过 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

【问题讨论】:

    标签: android post httpclient urlconnection


    【解决方案1】:

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

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

    【讨论】:

    • @Yati,是的,如上所述,出现此错误的原因是由于 auth 标头末尾的无关字符。通过修剪标题以消除这些空格来检查你的
    猜你喜欢
    • 1970-01-01
    • 2021-01-15
    • 2011-12-15
    • 2018-02-09
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    相关资源
    最近更新 更多