苍穹外卖 HTTP Client 调用
public class HttpClientTest {
/**
* 通过httpClient 发送get 请求
*/
@Test
public void testGet() throws IOException {
// 创建httpclient 对象
CloseableHttpClient aDefault = HttpClients.createDefault();
//创建请求对象
HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");
//发送请求
CloseableHttpResponse response = aDefault.execute(httpGet);
System.out.println("服务端返回状态码:"+response.getStatusLine());
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
System.out.println("服务端返回数据为:"+result);
//关闭连接
response.close();
aDefault.close();
}
@Test
public void testPost() throws IOException {
//创建连接
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
//构造请求对象
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","admin");
jsonObject.put("password","123456");
String string = jsonObject.toString();
StringEntity stringEntity = new StringEntity(string);
// 请求对象设置http格式
stringEntity.setContentEncoding("utf-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
// 发送响应
CloseableHttpResponse response = client.execute(httpPost);
System.out.println("响应码"+response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
String string1 = EntityUtils.toString(entity);
System.out.println("响应体"+string1);
// 关闭连接
response.close();
client.close();
}
}