1. pom.xml 引入坐标
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
2.测试
发送GET请求
//1.创建客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
//2.声明get请求
HttpGet request = new HttpGet("http://www.baidu.com");
//3.发送请求
CloseableHttpResponse response = httpClient.execute(request);
//4.判断状态码
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
//使用工具类EntityUtils,从响应中取出实体表示的内容并转换成字符串
String string = EntityUtils.toString(entity, "UTF-8");
System.out.println(string);
}
//5.关闭资源
response.close();
httpClient.close();
发送POST请求
//获取客户端
CloseableHttpClient client = HttpClients.createDefault();
//声明POST请求
HttpPost request = new HttpPost("https://gitee.com/oauth/token");
//设置User-Agent
request.addHeader("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");
//构建请求参数
ArrayList<NameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
parameters.add(new BasicNameValuePair("code", "xxx"));
parameters.add(new BasicNameValuePair("client_id", "xxx"));
parameters.add(new BasicNameValuePair("client_secret", "xxx"));
parameters.add(new BasicNameValuePair("redirect_uri", "http://localhost:8001/oauth/gitee/callback"));
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
//设置请求的参数
request.setEntity(urlEncodedFormEntity);
//发送请求
CloseableHttpResponse response = client.execute(request);
System.out.println(response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity, "UTF-8");
System.out.println(body);
} else {
System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));
}
//关闭资源
response.close();
client.close();