2012-10-24 11 views
41

私はandroid-async-httpを使用していて、本当に好きです。 POSTingデータで問題が発生しました。私は次の形式でAPIにデータをポストする必要があります: - ドキュメントあたりとしてandroid-async-http(loopj)を使用してJSON/XMLをポストする

<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もPOSTできます。何か案は?

答えて

106

Loopj POSTの例を設定します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

それがループJ –

+0

おかげチモシーその素敵な」 –

+0

おかげティモシーとハツカネズミのために動作します。 –

0

xmlまたはjsonを文字列に書き込み、適切なヘッダーを付けたまま、またはせずにサーバーに送信するだけです。

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

投稿するには:

private static AsyncHttpClient client = new AsyncHttpClient(); 

RequestParams経由で正常に投稿する:自分のTwitterの例から伸び - はい "のContent-Type" に "アプリケーション/ 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

@ティモシーの回答は私のためには機能しませんでした。

私はそれを動作させるために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

のリクエストを送信していましたが、「HttpEntityがコンテンツタイプを設定するため、渡されたcontentTypeは無視されます」というメッセージが送信されました。 私はあなたがここで言及したものを正確にやっています。 –

+0

ありがとう、ありがとう、ありがとう!エンティティと投稿の両方にContentTypeを設定すると、それは私のために働いています。 – user2408952

+1

@SalmanKhanはい、それはまだそれのように動作します。 あなたが*両方の*エンティティとUser2408952のような投稿にContentTypeを設定していることを確認してください。 – 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

あなたはいくつかの種類のInputStreamとしてJSON文字列を追加することができます - 私はあなたがJSONObject

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

だけで作るcorrectMimeTypeを設定し、その後にそれを変換する必要があり、その後RequestParamsに渡し、ByteArrayStreamを使用しました"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

PHPサーバーにxmlファイルを投稿するには、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

を投稿するためのより良い方法:

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

}

アンドロイド-非同期HTTPを-1.4.9を追加した後。アンドロイドスタジオへの瓶、 ビルドに移動します。Gradleのと追加:依存関係

下でのAndroidManifest.xmlに compile 'com.loopj.android:android-async-http:1.4.9'追加:

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

関連する問題