1. 引入 maven 依賴
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
2. 發(fā)送 GET 方式的請求
package com.zxe;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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
public class HttpClient {
@Test
public void test() throws Exception {
//1.創(chuàng)建httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
//2.創(chuàng)建請求對象
HttpGet httpGet = new HttpGet("http://localhost:8080/user/status");
//3.發(fā)送請求,接收響應結果
CloseableHttpResponse response = httpClient.execute(httpGet);
//4.獲取服務端返回的狀態(tài)碼
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("服務端返回的狀態(tài)碼為:" + statusCode);
//5.解析響應體
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);
System.out.println("服務端返回的數(shù)據(jù)為:" + body);
//6.關閉資源
response.close();
httpClient.close();
}
}
文章來源:http://www.zghlxwxcb.cn/news/detail-656114.html
3. 發(fā)送 POST 方式的請求
package com.zxe;
import org.apache.http.HttpEntity;
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.json.JSONObject;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class HttpClient {
@Test
public void test() throws Exception {
//1.創(chuàng)建httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
//2.創(chuàng)建請求對象
HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
//3.設置請求體參數(shù)
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "admin");
jsonObject.put("password", "123456");
StringEntity entity = new StringEntity(jsonObject.toString());
entity.setContentEncoding("utf-8");
//4.數(shù)據(jù)格式
entity.setContentType("application/json");
httpPost.setEntity(entity);
//5.發(fā)送請求,接收響應結果
CloseableHttpResponse response = httpClient.execute(httpPost);
//4.獲取服務端返回的狀態(tài)碼
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("服務端返回的狀態(tài)碼為:" + statusCode);
//5.解析響應體
HttpEntity entity1 = response.getEntity();
String body = EntityUtils.toString(entity1);
System.out.println("服務端返回的數(shù)據(jù)為:" + body);
//6.關閉資源
response.close();
httpClient.close();
}
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-656114.html
到了這里,關于通過 HttpClient 發(fā)送請求的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!