使用 org.apache.http.client.HttpClient;
一开始从官网下载HttpClient 4.5:http://hc.apache.org/downloads.cgi ,解压之后添加到项目,添加 httppost.setEntity(entity) 后,一执行 httpclient.execute(post) 就报错,不添加还能正常Post。
查了不少 stackoverflow 的帖子,测试了无数方法,终于在十二小时后,发现了答案:http://stackoverflow.com/questions/29788479/android-httpclient-nosuchmethoderrororg-apache-http-entity-contenttype-create
1、要用 httpclient-android-4.3.5.1.jar ,而不是 httpclient-4.5.jar ,重点是 android ,不是版本;
2、要用 httpmime-4.3.6.jar ,而不是最新的 httpmime-4.5.jar 。上面 stackoverflow 的帖子说了,httpmime 和 httpclient-android 存在不兼容问题。
3、MultipartEntityBuilder ,而不是 MultipartEntity 。
代码参考 开源软件凡信:http://www.imgeek.org/forum.php?mod=viewthread&tid=763&extra=page%3D1
new Thread() { @SuppressWarnings("rawtypes") public void run() { HttpClient client = new DefaultHttpClient(); MultipartEntityBuilder entity = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE); Set keys = map.keySet(); if (keys != null) { Iterator iterator = keys.iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); String value = (String) map.get(key); if (key.equals("file")) { File file = new File(value); entity.addPart(key, new FileBody(file)); } else { try { entity.addPart(key, new StringBody(value, Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } // 如果包含数组,要把包含的数组放进去,项目目前只有members这个数组,所有固定键值,为了更灵活 // 可以将传入自定义的键名...... if (has_Array) { for (int i = 0; i < members.size(); i++) { try { entity.addPart( "members[]", new StringBody(members.get(i), Charset .forName("UTF-8"))); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } client.getParams().setParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, 30000); // 请求超时 client.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, 30000); /*HttpPost post = new HttpPost(url); post.setEntity(entity);*/ HttpPost post = new HttpPost(url); post.setEntity(entity.build()); Log.d("LoadDataFromServer","2"); StringBuilder builder = new StringBuilder(); try { Log.d("LoadDataFromServer","3"); HttpResponse response = client.execute(post); Log.d("LoadDataFromServer","4"); if (response.getStatusLine().getStatusCode() == 200) { BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity() .getContent(), Charset.forName("UTF-8"))); for (String s = reader.readLine(); s != null; s = reader .readLine()) { builder.append(s); } String builder_BOM = jsonTokener(builder.toString()); System.out.println("返回数据是------->>>>>>>>" + builder.toString()); try { JSONObject jsonObject = new JSONObject(); jsonObject = JSONObject.parseObject(builder_BOM); Message msg = new Message(); msg.what = 111; msg.obj = jsonObject; handler.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }.start();