2012-10-24 48 views
41

我正在使用android-async-http并非常喜欢它。我遇到了有关发布数据的问题。我必须将数据发布到以下格式的API: -使用android-async-http发布JSON/XML(loopj)

<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。有任何想法吗?

回答

106

循环J 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); 
+1

它适用于循环Ĵ –

+0

感谢蒂莫西其漂亮的” –

+0

感谢提摩太和小家鼠。 –

0

只需将您的xml或json写入一个字符串并发送到服务器,并使用正确的标头或不带。和是设定 “内容类型” 为 “application/JSON”

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

@Timothy回答对我来说并不适用。

我定义的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); 

好运:)

+0

- “通过的contentType将被忽略,因为HttpEntity设置内容类型”。 我正在做你刚才在这里提到的。 –

+0

谢谢,谢谢,谢谢!设置ContentType的实体和邮政调用让它为我工作。 – user2408952

+1

@SalmanKhan是的,没关系,它仍然是这样的。 确保你已经设置ContentType * *实体和后像user2408952说。 – Danpe

0

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

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

+0

所以我应该怎么做,如果我想使用loopj发送JSON数据。 –

+0

@SalmanKhan //只需添加HttpClient.addHeader(“Content-Type”,“application/json”);在你的'.post(...);'方法之上。 – Youngjae

0

您可以添加JSON字符串作为某种类型的InputStream的 - 我用ByteArrayStream,然后将它传递给RequestParams你应该设置correctMimeType

InputStream stream = new ByteArrayInputStream(jsonParams.toString().getBytes(Charset.forName("UTF-8"))); 
multiPartEntity.put("model", stream, "parameters", Constants.MIME_TYPE_JSON); 
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); 

这是为我工作的罚款。

3

一个更好的方式来发布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) { 
     } 
    }); 
+1

此方法不适用于嵌套JSON –

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系统的异步HTTP-1.4.9之后。 jar to android studio, 去建立。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" />