基于HttpClient的工具类HttpUtil



org.apache.httpcomponents
httpclient
4.5.6




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 param) throws Exception {
HttpPost httpPost = new HttpPost(url);
ArrayList arrayList = new ArrayList();
Set 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网络爬虫

网络爬虫攻防常见技巧

你可能感兴趣的:(基于HttpClient的工具类HttpUtil)