HttpClient学习
背景
昨天快要下班的时候,被同事留下帮忙一起看HttpClient的问题,当时是一个json类型的请求使用的表单的请求方式,
导致请求报错。虽然说后面问题被解决了,但是还是觉得基础不够扎实,所以需要补充一下,已备查用。
测试原生的API
引入jar包
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
使用原生URL调用查询bing首页
代码
@Test
public void testOriginalUrl() throws Exception {
String bingUrl = "https://cn.bing.com/";
URL url = new URL(bingUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
try(
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
) {
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}