基于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网络爬虫
网络爬虫攻防常见技巧
标签:基于,return,String,url,execute,new,HttpUtil,response,HttpClient 来源: https://www.cnblogs.com/maoxiangyi/p/11647858.html