0

コンテキスト:Androidで、以下に示すようにJavaのHttpURLConnectionオブジェクトを使用すると、サーバー側でPOST本体が正しく表示されます。ただし、同等のHttpClientコードであると私が信じているものを使用すると、POST本文は空になります。

質問

  1. 私は何が欠けていますか?

  2. サーバー側はDjango-pythonサーバーです。このエンドポイントのエントリポイントにデバッグポイントを設定しましたが、投稿の本文はすでに空です。本体がnullである理由を見つけるために、どのようにデバッグできますか?

:私はすでにこれを見ましが、解決策は私にはうまくいきません。

コード: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
4

1 に答える 1

1

これが起こっている理由を考えました:

POST リクエストの承認ヘッダーに余分な改行文字 "\n" が含まれていました。これにより、リクエストがサーバー側のハンドラーに渡されましたが、本文が途切れていました。私はこれまでこの行動に気づいたことがありません。

于 2012-06-30T00:15:52.833 に答える