使用android-async-http(loopj)发布JSON / XML

我使用的是android-async-http ,真的很喜欢它。 我遇到POST数据的问题。 我必须以以下格式将数据发布到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。 有任何想法吗?

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); 

蒂莫西的回答对我没有用。

我定义了StringEntityContent-Type来使其工作:

 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); 

祝你好运 :)

一个更好的方式发布json

 RequestParams params = new RequestParams(); params.put("id", propertyID); params.put("lt", newPoint.latitude); params.put("lg", newPoint.longitude); params.setUseJsonStreamer(true); ScaanRestClient restClient = new ScaanRestClient(getApplicationContext()); restClient.post("/api-builtin/properties/v1.0/edit/location/", params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } }); 

发布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 }); } 

只需将你的xml或json写入一个string,然后发送到服务器,使用适当的头文件或不带。 是的“Content-Type”设置为“application / json”

如果有人遇到httpclient作为Content-Type: text/plain发送的问题,请参考以下链接: https : //stackoverflow.com/a/26425401/361100

loopj httpclient有些改变(或有问题),不能覆盖StringEntity原生Content-Type到application/json

你可以添加JSONstring作为InputStream的某种 – 我已经使用ByteArrayStream,然后传递给RequestParams你应该设置correctMimeType

 InputStream stream = new ByteArrayInputStream(jsonParams.toString().getBytes(Charset.forName("UTF-8"))); multiPartEntity.put("model", stream, "parameters", Constants.MIME_TYPE_JSON); 

只要使JSONObject,然后将其转换为string“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); 

它对我来说工作得很好。

要将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 studio中添加android-async-http-1.4.9.jar后,进入build.gradle并添加:在依赖compile 'com.loopj.android:android-async-http:1.4.9'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" />