httpclient用法,发送get和post请求,设置header
时间: 2024-04-11 11:27:48 浏览: 89
httpclient发送post请求
对于使用 HttpClient 发送 GET 请求,可以按照以下步骤进行操作:
1. 导入 `org.apache.http.client.methods.HttpGet` 和 `org.apache.http.impl.client.CloseableHttpClient` 类:
```java
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
```
2. 创建 HttpClient 对象:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
```
3. 创建 HttpGet 对象,并设置请求的 URL:
```java
HttpGet httpGet = new HttpGet("http://example.com/api");
```
4. 可选:设置请求头部信息:
```java
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Authorization", "Bearer token");
```
5. 发送请求并获取响应:
```java
CloseableHttpResponse response = httpClient.execute(httpGet);
```
6. 处理响应结果:
```java
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
```
7. 关闭 HttpClient 和响应对象:
```java
response.close();
httpClient.close();
```
使用 HttpClient 发送 POST 请求的步骤类似,只需将上述代码中的 `HttpGet` 替换为 `HttpPost`,并设置请求的方法为 POST。
希望对你有所帮助!如有其他问题,请随时提问。
阅读全文