Android AsyncHttpClient:如何POST多部分表单数据?

时间:2015-11-11 11:44:55

标签: android androidhttpclient

AsyncHttpClient版本是1.4.7。 服务器收到请求,但找不到文件参数

2 个答案:

答案 0 :(得分:1)

工作示例

 HttpClient httpclient;
 HttpPost httppost;


 httpclient = new DefaultHttpClient();
 httppost = new HttpPost(URLRepo.URL_IMAGESAVE);


List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user_id", ""+deichapp.getInt("userid", 0)));
//.. add parameters
File file = new File(new URI(obj.getString("fileUri")));
nameValuePairs.add(new BasicNameValuePair("filename", file.getName()));

httpclient.getParams().setParameter("Connection", "Keep-Alive");
httpclient.getParams().setParameter("Content-Type", "multipart/form-data;");

MultipartEntityBuilder entity = MultipartEntityBuilder.create();
                    for (BasicNameValuePair nameValuePair : nameValuePairs) {
            entity.addTextBody(nameValuePair.getName(), nameValuePair.getValue());
                    }

entity.addPart("file", new FileBody(new File(new URI(obj.getString("fileUri")))));

httppost.setEntity(entity.build());

// Send and store the Image
HttpResponse response = httpclient.execute(httppost);
    String json;
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
json = reader.readLine();

这使用本机android api,没有像async http client这样的外部库。确保在后台线程上执行此代码。

答案 1 :(得分:0)

试试这个:

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

希望这有帮助!