httpclient测试怎么写
时间: 2024-04-28 08:25:08 浏览: 15
HttpClient 是一个用于发送 HTTP 请求的 Java 类库,它提供了许多方法来发送 GET、POST 等请求,并且可以设置请求头、请求体、超时时间等参数。下面提供一个简单的 HttpClient 测试代码示例:
```java
import java.io.IOException;
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;
public class HttpClientTest {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://www.example.com");
HttpPost httpPost = new HttpPost("http://www.example.com");
try {
// 发送 GET 请求
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
response.close();
// 发送 POST 请求
httpPost.setEntity(new StringEntity("param1=value1¶m2=value2"));
response = httpClient.execute(httpPost);
entity = response.getEntity();
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
response.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
此代码示例创建了一个默认的 CloseableHttpClient 对象,用于发送 HTTP 请求。然后分别创建了一个 HttpGet 和 HttpPost 对象,并设置请求的 URL。在发送 GET 请求时,使用 execute 方法发送请求,并通过 EntityUtils 将响应内容转换为字符串输出。在发送 POST 请求时,先设置请求的参数,然后再通过 execute 方法发送请求,并同样将响应内容转换为字符串输出。注意,执行完请求后需要关闭 CloseableHttpClient 对象。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)