【发布时间】:2014-06-04 23:21:18
【问题描述】:
我正在尝试从我的 Android 客户端发送 HTTP/HTTPS 发布请求。
问题
为什么我的代码会失败?
到目前为止
我创建了一个 apache 类/HttpClient 调用。一切正常:
HttpClient httpClient = new DefaultHttpClient();
我已阅读此方法已被弃用,因此我已切换到新的推荐方法:
HttpClient httpClient = HttpClientBuilder.create().build();
Eclipse 没有这个类,所以我不得不下载 Apache HttpClient 4.3.3。我通过将其复制到 libs 文件夹并将它们添加到我的构建路径(导入的 httpclient、httpclient-cache、httpcore、httpmime、fluent-hc、commons-logging、commons-codec)将其导入到我的项目中。
错误信息
06-05 02:15:26.946: W/dalvikvm(29587): Link of class 'Lorg/apache/http/impl/conn/PoolingHttpClientConnectionManager;' failed
06-05 02:15:26.946: E/dalvikvm(29587): Could not find class 'org.apache.http.impl.conn.PoolingHttpClientConnectionManager', referenced from method org.apache.http.impl.client.HttpClientBuilder.build
最近的代码
static private String insertJson(String json,String url){
HttpClient httpClient = HttpClientBuilder.create().build();
String responseString = "";
try {
HttpPost request = new HttpPost(url);
StringEntity params =new StringEntity(json, "UTF-8");
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
responseString = EntityUtils.toString(entity, "UTF-8");
}catch (Exception ex) {
ex.printStackTrace();
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
return responseString;
}
【问题讨论】:
-
它可能在更新的库版本中被弃用。但是 Android 使用的是旧版本。我不认为它在 Android 中已被弃用。
-
@matlash 弃用和完全删除是有区别的。
-
@EJP 但“新建议方法”(
HttpClientBuilder)在 Android 中甚至不存在。它是 httpclient 4.3 中的新功能,而 android 有 4.0beta2。DefaultHttpClient在该版本中尚未弃用,在 Android 中也未弃用。 -
加载apk时logcat中没有任何先前的警告吗?某些类可能无法加载,因为 previous 类失败。
标签: java android apache-httpclient-4.x apache-httpcomponents