基于HttpClient的工具类HttpUtil


<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>




public class HttpUtil {
public static String doGet(String url) throws Exception {
HttpGet httpGet = new HttpGet(url);
return execute(httpGet);
}

public static String doPost(String url, Map<String, String> param) throws Exception {
HttpPost httpPost = new HttpPost(url);
ArrayList<BasicNameValuePair> arrayList = new ArrayList<BasicNameValuePair>();
Set<String> keySet = param.keySet();
for (String key : keySet) {
arrayList.add(new BasicNameValuePair(key, param.get(key)));
}
httpPost.setEntity(new UrlEncodedFormEntity(arrayList));
return execute(httpPost);
}

private static String execute(HttpRequestBase request) throws IOException, ClientProtocolException {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(request);
if (200 == response.getStatusLine().getStatusCode()) {
return EntityUtils.toString(response.getEntity(), Charset.forName("utf-8"));
} else {
System.out.println(EntityUtils.toString(response.getEntity(), Charset.forName("utf-8")));
}
return "";
}

}


更多信息:

使用代理IP地址开发某网站自动投票程序

使用代理IP编写Java网络爬虫

网络爬虫攻防常见技巧

posted @ 2019-10-10 14:43  春江师兄  阅读(5244)  评论(0编辑  收藏  举报