47

我正在使用android-async-http并且非常喜欢它。我遇到了发布数据的问题。我必须以以下格式将数据发布到 API:-

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

4

9 回答 9

128

Loopj 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);
于 2012-12-16T13:19:40.093 回答
22

@Timothy 的回答对我不起作用。

我定义了Content-TypeofStringEntity以使其工作:

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

祝你好运 :)

于 2014-10-12T19:56:11.057 回答
7

发布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) {
        }
    });
于 2016-05-02T08:36:50.360 回答
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
    });
}
于 2013-05-17T05:51:32.633 回答
0

只需将您的 xml 或 json 写入字符串并发送到服务器,无论是否带有适当的标头。是的,将“Content-Type”设置为“application/json”

于 2012-10-24T15:41:25.373 回答
0

如果有人遇到 httpclient 发送的问题Content-Type: text/plain,请参考此链接: https ://stackoverflow.com/a/26425401/361100

loopj httpclient 发生了一些变化(或有问题),无法将StringEntity本机 Content-Type 覆盖为application/json.

于 2014-10-17T16:54:59.663 回答
0

您可以将 JSON 字符串添加为某种 InputStream - 我使用了 ByteArrayStream,然后将其传递给 RequestParams 您应该设置正确的MimeType

InputStream stream = new ByteArrayInputStream(jsonParams.toString().getBytes(Charset.forName("UTF-8")));
multiPartEntity.put("model", stream, "parameters", Constants.MIME_TYPE_JSON);
于 2015-01-28T12:37:30.923 回答
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);

它对我来说很好。

于 2016-03-10T19:18:25.013 回答
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-async-http-1.4.9.jar添加到android studio后,进入build.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" />

于 2016-05-25T10:15:57.500 回答