这是我制作的两个用于下载文件的小辅助方法。我必须混合搭配不同的网络教程才能获得我在这里的内容。
现在我在这里做错了什么吗?
public static InputStream simplePostRequest(URL url, List<NameValuePair> postData) throws ClientProtocolException, IOException {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost postMethod=new HttpPost(url.toExternalForm());
postMethod.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
HttpResponse response = httpclient.execute(postMethod);
HttpEntity entity = response.getEntity();
return entity.getContent();
}
public static InputStream simpleGetRequest(URL url, List<NameValuePair> queryString) throws ClientProtocolException, IOException {
Uri.Builder uri = new Uri.Builder();
uri.path(url.getPath());
for(NameValuePair nvp: queryString) {
uri.appendQueryParameter(nvp.getName(), nvp.getValue());
}
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpHost host = new HttpHost(url.getHost());
HttpResponse response = httpClient.execute(host, new HttpGet(uri.build().toString()));
HttpEntity entity = response.getEntity();
return entity.getContent();
}
最佳答案
对于这样一个含糊不清的问题,我没想到会有如此多的回应。为什么不编写一对单元测试来试用您的代码呢?
无论如何,根据我使用 HttpClient 的经验,对我来说突出的一件事是,如果承受重负载(大量并发线程),您的代码似乎不安全 - 似乎没有上限可以创建的并发连接。
如果您认为这可能与您的情况相关,您可以尝试这样的事情:
class X {
private static final HttpClient httpClient;
static {
SchemeRegistry defaultRegistery = new DefaultHttpClient().getConnectionManager()
.getSchemeRegistry();
ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(defaultRegistery);
connMgr.setMaxTotalConnections(10);
connMgr.setDefaultMaxPerRoute(10);
httpClient = new DefaultHttpClient(connMgr);
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
}
public static InputStream simpleGetRequest(URL url, List<NameValuePair> queryString) throws ClientProtocolException, IOException {...}
public static InputStream simpleGetRequest(URL url, List<NameValuePair> queryString) throws ClientProtocolException, IOException {...}
}
...并且只需在您的方法中使用静态 httpClient 而不是每次都实例化一个新方法。
我从我以前写的一些代码中复制并修改了这个,但不要认为这一定是正确的。单元测试将成为您的 friend 。
编辑:关于您关于混合 URL 和 HttpClient 库类 NameValuePair 的评论(这是您关心的问题吗?),为什么不只是方法签名中的 Map
关于java - 只需要熟悉 HTTPClient 的人检查一段代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2983562/