47

私はandroid-async-httpを使用していて、とても気に入っています。POSTing データで問題が発生しました。次の形式でデータを API に投稿する必要があります。

<request>
  <notes>Test api support</notes>
  <hours>3</hours>
  <project_id type="integer">3</project_id>
  <task_id type="integer">14</task_id>
  <spent_at type="date">Tue, 17 Oct 2006</spent_at>
</request>

ドキュメントに従って、 を使用して実行しようとしましRequestParamsたが、失敗しています。これを行う他の方法はありますか?同等の JSON も POST できます。何か案は?

4

9 に答える 9

128

Loopj POST の例 - Twitter の例から拡張:

private static AsyncHttpClient client = new AsyncHttpClient();

経由で通常どおり投稿するにはRequestParams:

RequestParams params = new RequestParams();
params.put("notes", "Test api support"); 
client.post(restApiUrl, params, responseHandler);

JSON を投稿するには:

JSONObject jsonParams = new JSONObject();
jsonParams.put("notes", "Test api support");
StringEntity entity = new StringEntity(jsonParams.toString());
client.post(context, restApiUrl, entity, "application/json",
    responseHandler);
于 2012-12-16T13:19:40.093 に答える
22

@ティモシーの答えはうまくいきませんでした。

Content-Type私はそれを機能させるために のを定義しましたStringEntity:

JSONObject jsonParams = new JSONObject();
jsonParams.put("notes", "Test api support");

StringEntity entity = new StringEntity(jsonParams.toString());
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

client.post(context, restApiUrl, entity, "application/json", responseHandler);

幸運を :)

于 2014-10-12T19:56:11.057 に答える
1

XML を投稿するには

protected void makePost() {
    AsyncHttpClient client = new AsyncHttpClient();
    Context context = this.getApplicationContext();
    String  url = URL_String;
    String  xml = XML-String;
    HttpEntity entity;
    try {
        entity = new StringEntity(xml, "UTF-8");
    } catch (IllegalArgumentException e) {
        Log.d("HTTP", "StringEntity: IllegalArgumentException");
        return;
    } catch (UnsupportedEncodingException e) {
        Log.d("HTTP", "StringEntity: UnsupportedEncodingException");
        return;
    }
    String  contentType = "string/xml;UTF-8";

    Log.d("HTTP", "Post...");
    client.post( context, url, entity, contentType, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(String response) {
            Log.d("HTTP", "onSuccess: " + response);
        }
          ... other handlers
    });
}
于 2013-05-17T05:51:32.633 に答える
0

JSON 文字列を何らかの InputStream として追加できます - 私は ByteArrayStream を使用してから、それを RequestParams に渡し、正しい MimeType を設定する必要があります

InputStream stream = new ByteArrayInputStream(jsonParams.toString().getBytes(Charset.forName("UTF-8")));
multiPartEntity.put("model", stream, "parameters", Constants.MIME_TYPE_JSON);
于 2015-01-28T12:37:30.923 に答える
0

JSONObject を作成し、それを文字列「someData」に変換して、「ByteArrayEntity」で送信するだけです。

    private static AsyncHttpClient client = new AsyncHttpClient();
    String someData;
    ByteArrayEntity be = new ByteArrayEntity(someData.toString().getBytes());
    client.post(context, url, be, "application/json", responseHandler);

それは私にとってはうまくいっています。

于 2016-03-10T19:18:25.013 に答える
0

xmlまたはjsonを文字列に書き込んで、適切なヘッダーを付けて、または付けずにサーバーに送信するだけです。はい、「Content-Type」を「application/json」に設定します

于 2012-10-24T15:41:25.373 に答える
0

httpclient が として送信する問題がある場合は、次のContent-Type: text/plainリンクを参照してください: https://stackoverflow.com/a/26425401/361100

loopj httpclient は多少変更されている (または問題がある) ため、StringEntityネイティブの Content-Type を にオーバーライドできませんapplication/json

于 2014-10-17T16:54:59.663 に答える
0

xml ファイルを php サーバーにポストするには:

public class MainActivity extends AppCompatActivity {

/**
 * Send xml file to server via asynchttpclient lib
 */

Button button;
String url = "http://xxx/index.php";
String filePath = Environment.getExternalStorageDirectory()+"/Download/testUpload.xml";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button)findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            postFile();
        }
    });
}

public void postFile(){

    Log.i("xml","Sending... ");

    RequestParams params = new RequestParams();

    try {
        params.put("key",new File(filePath));
    }catch (FileNotFoundException e){
        e.printStackTrace();
    }

    AsyncHttpClient client = new AsyncHttpClient();

    client.post(url, params, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes) {
            Log.i("xml","StatusCode : "+i);
        }

        @Override
        public void onFailure(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes, Throwable throwable) {
            Log.i("xml","Sending failed");
        }

        @Override
        public void onProgress(long bytesWritten, long totalSize) {
            Log.i("xml","Progress : "+bytesWritten);
        }
    });
}

}

android-async-http-1.4.9.jar を android studio に追加した後、build.gradle に移動し、 compile 'com.loopj.android:android-async-http:1.4.9'依存関係の下に : を追加します。

AndroidManifest.xml に以下を追加します。

<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

于 2016-05-25T10:15:57.500 に答える