2012-10-24 11 views
41

Sto usando android-async-http e mi piace davvero. Ho incontrato un problema con i dati POST. Devo inviare i dati alle API nel seguente formato: -POSTing JSON/XML con android-async-http (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> 

Come per la documentazione, ho provato a farlo usando RequestParams, ma sta fallendo. Questo è un altro modo per farlo? Posso anche POST JSON equivalente. Qualche idea?

risposta

106

Loopj POST - esteso dal loro Twitter esempio:

private static AsyncHttpClient client = new AsyncHttpClient(); 

di inviare normalmente via RequestParams:

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

Inserisci 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

funziona ciclo for j –

+0

grazie Timothy la sua bella' –

+0

Grazie Timoteo e Mus. –

0

basta scrivere il tuo xml o json su una stringa e inviarlo al server, con intestazioni appropriate o senza. e sì impostare "Content-Type" a "application/json"

esempi
1

Per pubblicare 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

@Timotea risposta non ha funzionato per me.

ho definito il Content-Type del StringEntity per farlo funzionare:

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

Buona fortuna :)

+0

durante l'invio della richiesta dice: "Il contentType passato verrà ignorato perché HttpEntity imposta il tipo di contenuto". Sto facendo esattamente quello che hai menzionato qui. –

+0

Grazie, grazie, grazie! impostando ContentType su ENTRAMBI l'entità e la chiamata post ha funzionato per me. – user2408952

+1

@SalmanKhan Sì, va bene funziona ancora così. assicurati di aver impostato ContentType su * both * entity e post come user2408952 detto. – Danpe

0

Se qualcuno ha un problema che httpclient inviare come Content-Type: text/plain, consultare questo link: https://stackoverflow.com/a/26425401/361100

Il loopj httpclient è in qualche modo modificato (o presenta un problema) che non può ignorare il tipo di contenuto nativo StringEntity su application/json.

+0

quindi cosa devo fare se voglio inviare dati JSON usando loopj. –

+0

@SalmanKhan // aggiungi semplicemente HttpClient.addHeader ("Content-Type", "application/json"); sopra il tuo metodo '.post (...);'. – Youngjae

0

È possibile aggiungere la stringa JSON come un InputStream di qualche tipo - Ho usato il ByteArrayStream, passando poi agli RequestParams si dovrebbe impostare la correctMimeType

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

Basta fare JSONObject e quindi convertirlo in String "someData" e inviate semplicemente con "ByteArrayEntity"

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

si sta lavorando bene per me.

3

un modo migliore per inviare 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

questo metodo non funziona per JSON nidificato –

0

Per pubblicare file XML a un server 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); 
     } 
    }); 
} 

}

Dopo aver aggiunto android-async-http-1.4.9. jar to android studio, andare a costruire.Gradle e aggiungere: compile 'com.loopj.android:android-async-http:1.4.9' sotto le dipendenze

E su AndroidManifest.xml aggiungere:

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

Problemi correlati