package com.sky.text;
import com.google.gson.JsonObject;
import com.sky.SkyApplication;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(classes = SkyApplication.class)
public class HttpClientText {
* 通过HttpClient发送GET请求
*/
@Test
public void testGet() throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
if (statusCode == 200) {
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(result);
}
response.close();
httpClient.close();
}
* 通过HttpClient发送POST请求
*/
@Test
public void testPost() throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("username", "admin");
jsonObject.addProperty("password", "123456");
StringEntity stringEntity = new StringEntity(jsonObject.toString());
stringEntity.setContentEncoding("utf-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
httpPost.setHeader("Content-Type", "application/json");
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
if (statusCode == 200) {
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(result);
}
response.close();
httpClient.close();
}
}