<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
代码:
public class Test {
public static void main(String[] args) {
System.out.println(doGet("http://www.baidu.com"));
}
/**
* 测试get请求方式
*
* @param apiUrl 链接
* @return 请求返回值
* @author 明快de玄米61
* @date 2021/09/05
*/
private static String doGet(String apiUrl) {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
// 创建客户端连接对象
client = HttpClients.createDefault();
// 构建Get请求对象
HttpGet get = new HttpGet(apiUrl);
// 设置超时时间,其中connectionRequestTimout(从连接池获取连接的超时时间)、connetionTimeout(客户端和服务器建立连接的超时时间)、socketTimeout(客户端从服务器读取数据的超时时间),单位都是毫秒
RequestConfig config = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(3000)
.setSocketTimeout(20000).build();
get.setConfig(config);
// 获取返回对象
response = client.execute(get);
// 整理返回值
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
// 关闭连接和流
try {
if (client != null) {
client.close();
}
if (response != null) {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
结果:
<!DOCTYPE html><!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129>