依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
这里注意如果你选择Get访问,问号传参的话,不能带上中文,如果需要中文,请转码后在拼接字符串在访问
// 请求访问时必须将中文字符转成URLEncode
String encode = URLEncoder.encode(bookName, "utf-8");
不然就会报错!
以下是示例代码:
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建Get请求
String response = null;
try {
// 请求访问时必须将中文字符转成URLEncode
// String encode = URLEncoder.encode(bookName, "utf-8");
HttpGet httpGet = new HttpGet("https://www.baidu.com/");
// 执行请求
CloseableHttpResponse execute = httpClient.execute(httpGet);
// 获取实例
HttpEntity entity = execute.getEntity();
response = EntityUtils.toString(entity, "UTF-8");
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}