Android AsyncHttpClient: how to POST multipart form data?

喜你入骨 提交于 2019-12-23 04:32:38

问题


The AsyncHttpClient version is 1.4.7. The server recieves the request, but could not find the file param


回答1:


Working example

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

This uses the native android api and no external librarys like async http client. Make sure you execute this code on a background thread.




回答2:


Try this:

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

Hope this helps!



来源:https://stackoverflow.com/questions/33649852/android-asynchttpclient-how-to-post-multipart-form-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!