前言介绍
总结就是使得可以在java程序中发送http请求。
导入依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
发送get请求
用到如下的一个url,不需要参数
https://yapi.pro/mock/17601/yhy2002
每次会返回一些不同的字符串。
代码如下所示
@Test
void testGet() throws IOException {
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建请求对象
HttpGet httpGet = new HttpGet("https://yapi.pro/mock/17601/yhy2002");
//发送请求
CloseableHttpResponse response = httpClient.execute(httpGet);
//获取服务端返回的状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
//获取响应数据
HttpEntity entity = response.getEntity();
//解析响应
String s = EntityUtils.toString(entity);
System.out.println(s);
//关闭资源
response.close();
httpClient.close();
}
输出有:
发送post请求
使用到如下的链接
https://yapi.pro/mock/17601/yhy2003
需要两个参数username,password,还有指定contentType为application/json,这里不需要指定编码格式
@Test
void testPost() throws IOException, JSONException {
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建请求对象
HttpPost httpPost = new HttpPost("https://yapi.pro/mock/17601/yhy2003");
//将json格式参数转换字符串
JSONObject jsonObject=new JSONObject();
jsonObject.put("username","yhy");
jsonObject.put("password","123456");
StringEntity stringEntity=new StringEntity(jsonObject.toString());
//指定编码方式
// stringEntity.setContentEncoding("utf-8");
//指定数据格式
stringEntity.setContentType("application/json");
//设置请求参数
httpPost.setEntity(stringEntity);
//发送请求
CloseableHttpResponse response = httpClient.execute(httpPost);
//获取服务端返回的状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
//获取响应数据
HttpEntity entity = response.getEntity();
//解析响应
String s = EntityUtils.toString(entity);
System.out.println(s);
//关闭资源
response.close();
httpClient.close();
}
输出为随机字符串