2012-10-24 46 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" />