HttpClient的GET(POST)请求

一。不带参数的GET请求的方法:

 

// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();

// 创建http GET请求
HttpGet httpGet = new HttpGet("http://www.baidu.com/");

CloseableHttpResponse response = null;
try {
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println("内容长度:"+content.length());
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();

 

二。带参数的GET请求 

// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();

// 定义请求的参数
URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();

System.out.println(uri);

// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);

CloseableHttpResponse response = null;
try {
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}

 

三。不带参数的post请求

 

// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();

// 创建http POST请求
HttpPost httpPost = new HttpPost("http://www.oschina.net/");
//设置请求头信息,可以伪装成浏览器访问
httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");

CloseableHttpResponse response = null;
try {
// 执行请求
response = httpclient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}

 四。带参数的post请求

 

// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();

// 创建http POST请求
HttpPost httpPost = new HttpPost("http://www.oschina.net/search");

// 设置2个post参数,一个是scope、一个是q
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
parameters.add(new BasicNameValuePair("scope", "project"));
parameters.add(new BasicNameValuePair("q", "java"));
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 将请求实体设置到httpPost对象中
httpPost.setEntity(formEntity);

CloseableHttpResponse response = null;
try {
// 执行请求
response = httpclient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}

 

posted @ 2018-08-25 10:30  梦浍烈风灵  阅读(183)  评论(0编辑  收藏  举报