J’utilise android-async-http et je l’aime vraiment. J’ai rencontré un problème avec les données POSTing. Je dois publier des données sur l’API au format suivant: –
Test api support 3 3 14 Tue, 17 Oct 2006
Selon la documentation, j’ai essayé de le faire en utilisant RequestParams
, mais cela échoue. Est-ce une autre façon de le faire? Je peux aussi poster un JSON équivalent. Des idées?
Exemples Loopj POST – étendus à partir de leur exemple Twitter:
private static AsyncHttpClient client = new AsyncHttpClient();
Pour poster normalement via RequestParams
:
RequestParams params = new RequestParams(); params.put("notes", "Test api support"); client.post(restApiUrl, params, responseHandler);
Pour publier JSON:
JSONObject jsonParams = new JSONObject(); jsonParams.put("notes", "Test api support"); SsortingngEntity entity = new SsortingngEntity(jsonParams.toSsortingng()); client.post(context, restApiUrl, entity, "application/json", responseHandler);
@Timothy réponse n’a pas fonctionné pour moi.
J’ai défini le Content-Type
de Content-Type
de SsortingngEntity
pour le faire fonctionner:
JSONObject jsonParams = new JSONObject(); jsonParams.put("notes", "Test api support"); SsortingngEntity entity = new SsortingngEntity(jsonParams.toSsortingng()); entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); client.post(context, restApiUrl, entity, "application/json", responseHandler);
Bonne chance 🙂
une meilleure façon de poster 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) { } });
Pour poster XML
protected void makePost() { AsyncHttpClient client = new AsyncHttpClient(); Context context = this.getApplicationContext(); Ssortingng url = URL_Ssortingng; Ssortingng xml = XML-Ssortingng; HttpEntity entity; try { entity = new SsortingngEntity(xml, "UTF-8"); } catch (IllegalArgumentException e) { Log.d("HTTP", "SsortingngEntity: IllegalArgumentException"); return; } catch (UnsupportedEncodingException e) { Log.d("HTTP", "SsortingngEntity: UnsupportedEncodingException"); return; } Ssortingng contentType = "ssortingng/xml;UTF-8"; Log.d("HTTP", "Post..."); client.post( context, url, entity, contentType, new AsyncHttpResponseHandler() { @Override public void onSuccess(Ssortingng response) { Log.d("HTTP", "onSuccess: " + response); } ... other handlers }); }
écrivez simplement votre fichier XML ou JSON dans une chaîne et envoyez-le au serveur, avec des en-têtes appropriés ou sans. et oui, réglez “Content-Type” sur “application / json”
Si quelqu’un a un problème que httpclient envoie en tant que Content-Type: text/plain
, veuillez vous référer à ce lien: https://stackoverflow.com/a/26425401/361100
La boucle httpclient est quelque peu modifiée (ou a un problème) qui ne peut pas remplacer SsortingngEntity
natif Content-Type par application/json
.
Vous pouvez append la chaîne JSON comme un InputStream de quelque sorte – J’ai utilisé le ByteArrayStream, puis le passer aux RequestParams, vous devez définir le correctMimeType
InputStream stream = new ByteArrayInputStream(jsonParams.toSsortingng().getBytes(Charset.forName("UTF-8"))); multiPartEntity.put("model", stream, "parameters", Constants.MIME_TYPE_JSON);
Créez simplement JSONObject puis convertissez-le en Ssortingng “someData” et envoyez simplement avec “ByteArrayEntity”
private static AsyncHttpClient client = new AsyncHttpClient(); Ssortingng someData; ByteArrayEntity be = new ByteArrayEntity(someData.toSsortingng().getBytes()); client.post(context, url, be, "application/json", responseHandler);
Cela fonctionne très bien pour moi.
Pour poster un fichier xml sur un serveur php:
public class MainActivity extends AppCompatActivity { /** * Send xml file to server via asynchttpclient lib */ Button button; Ssortingng url = "http://xxx/index.php"; Ssortingng 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); } }); }
}
Après avoir ajouté android-async-http-1.4.9.jar au studio Android, allez dans build.gradle et ajoutez: comstack 'com.loopj.android:android-async-http:1.4.9'
sous dépendances
Et sur AndroidManifest.xml, ajoutez: