public class HttpClientTest {
/**
* 使用HttpClient 发送Get 请求
*/
@Test
public void testGet1() {
//可关闭的httpClient 客户端,相当于打开的浏览器
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
String url = "https://www.baidu.com";
//构造HttpClient 请求对象
HttpGet httpGet = new HttpGet(url);
//解决httpClient 认为不是真人行为
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36");
//防盗链
httpGet.addHeader("Referer", "https://www.baidu.com/");
//响应
CloseableHttpResponse response = null;
try {
response = closeableHttpClient.execute(httpGet);
//获取响应结果
HttpEntity entity = response.getEntity();
//HttpClient 工具
String toStringRusult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println(toStringRusult);
//确保流关闭
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (closeableHttpClient != null) {
try {
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void testGet2() throws UnsupportedEncodingException {
//可关闭的httpClient 客户端,相当于打开的浏览器
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
String name = "Dave+123|abdc 000";
int age = 15;
name = URLEncoder.encode(name, StandardCharsets.UTF_8.name());
String url = "http://192.168.10.115:9999/test/testController1?age=" + age + "&name=" + name;
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = null;
try {
response = closeableHttpClient.execute(httpGet);
//请求状态
StatusLine statusLine = response.getStatusLine();
System.out.println("请求状态" + statusLine);
if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
System.out.println("请求成功");
Header[] allHeaders = response.getAllHeaders();
for (Header header : allHeaders) {
System.out.println("响应头" + header.getName() + ";响应内容:" + header.getValue());
}
//获取响应结果
HttpEntity entity = response.getEntity();
System.out.println("ContentType:" + entity.getContentType());
//HttpClient 工具
String toStringRusult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println(toStringRusult);
//确保流关闭
EntityUtils.consume(entity);
} else {
System.out.println("响应失败");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (closeableHttpClient != null) {
try {
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//获取网络图片下载
@Test
public void testGet3() throws Exception {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
String url = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fdpic.tiankong.com%2Fii%2Fw0%2FQJ6643282250.jpg%3Fx-oss-process%3Dstyle%2Fshows&refer=http%3A%2F%2Fdpic.tiankong.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640341198&t=338b118e4678ad3e5d3be5d6e9d3f061";
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = null;
try {
response = closeableHttpClient.execute(httpGet);
//获取响应结果
HttpEntity entity = response.getEntity();
String contentType = entity.getContentType().getValue();
String suffix = null;
if (contentType.contains("jpg") || contentType.contains("jpeg")) {
suffix = ".jpg";
} else if (contentType.contains("bmp") || contentType.contains("bitmap")) {
suffix = ".bmp";
} else if (contentType.contains("png")) {
suffix = ".png";
} else if (contentType.contains("gif")) {
suffix = ".gif";
}
//获取文件字节流
byte[] bytes = EntityUtils.toByteArray(entity);
String localAbsPath = "test_photo/abc" + suffix;
FileOutputStream fos = new FileOutputStream(localAbsPath);
fos.write(bytes);
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (closeableHttpClient != null) {
try {
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//设置访问代理
@Test
public void testGet4() {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
String url = "https://www.baidu.com";
HttpGet httpGet = new HttpGet(url);
//创建一个代理
String ip = "115.223.7.34";
int port = 80;
HttpHost proxy = new HttpHost(ip, port);
//针对每个请求特殊的定制
RequestConfig requestConfig = RequestConfig.custom()
.setProxy(proxy)
//连接超时,tcp 三次握手的时间上限
.setConnectTimeout(5000)
//读取时间超时ms,表示从请求的网址处获得响应数据的时间间隔
.setSocketTimeout(3000)
.build();
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
response = closeableHttpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String toStringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println(toStringResult);
EntityUtils.consume(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (closeableHttpClient != null) {
try {
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//测试post 请求
@Test
public void testPost1() throws UnsupportedEncodingException {
//可关闭的httpClient 客户端,相当于打开的浏览器
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
String url = "http://192.168.10.115:9999/test/testController2";
HttpPost httpPost = new HttpPost(url);
//给Post 对象设置参数
// NameValuePair input 标签里面输入的值
List<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("name","张三"));
list.add(new BasicNameValuePair("age","100"));
//把参数集合设置给FormEntity
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list,Consts.UTF_8);
httpPost.setEntity(formEntity);
CloseableHttpResponse response = null;
try {
response = closeableHttpClient.execute(httpPost);
//请求状态
StatusLine statusLine = response.getStatusLine();
System.out.println("请求状态" + statusLine);
if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
System.out.println("请求成功");
Header[] allHeaders = response.getAllHeaders();
for (Header header : allHeaders) {
System.out.println("响应头" + header.getName() + ";响应内容:" + header.getValue());
}
//获取响应结果
HttpEntity entity = response.getEntity();
System.out.println("ContentType:" + entity.getContentType());
//HttpClient 工具
String toStringRusult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println(toStringRusult);
//确保流关闭
EntityUtils.consume(entity);
} else {
System.out.println("响应失败");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (closeableHttpClient != null) {
try {
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//发送 application/json 类型的 post 请求
@Test
public void testPost2() throws UnsupportedEncodingException {
//可关闭的httpClient 客户端,相当于打开的浏览器
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
String url = "http://192.168.10.115:9999/test/testController2";
HttpPost httpPost = new HttpPost(url);
//设置实体
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","小可爱");
jsonObject.put("age",31);
StringEntity jsonEntity = new StringEntity(String.valueOf(jsonObject),Consts.UTF_8);
//给entity 设置内容类型
jsonEntity.setContentType(new BasicHeader("Content-Type","application/json;charset=utf-8"));
//设置编码
jsonEntity.setContentEncoding(Consts.UTF_8.name());
httpPost.setEntity(jsonEntity);
CloseableHttpResponse response = null;
try {
response = closeableHttpClient.execute(httpPost);
//请求状态
StatusLine statusLine = response.getStatusLine();
System.out.println("请求状态" + statusLine);
if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
System.out.println("请求成功");
Header[] allHeaders = response.getAllHeaders();
for (Header header : allHeaders) {
System.out.println("响应头" + header.getName() + ";响应内容:" + header.getValue());
}
//获取响应结果
HttpEntity entity = response.getEntity();
System.out.println("ContentType:" + entity.getContentType());
//HttpClient 工具
String toStringRusult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println(toStringRusult);
//确保流关闭
EntityUtils.consume(entity);
} else {
System.out.println("响应失败");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (closeableHttpClient != null) {
try {
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
|