HttpClient请求代码案例
时间: 2024-09-24 18:27:47 浏览: 37
HttpClient是Apache HttpComponents库的一部分,用于发送HTTP请求。以下是一个简单的Java示例,展示如何使用HttpClient发送GET和POST请求:
```java
import org.apache.http.HttpResponse;
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;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
// 创建HttpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 发送GET请求
HttpGet get = new HttpGet("http://example.com/api/data");
HttpResponse response = httpClient.execute(get);
System.out.println("GET Response: " + response.getStatusLine());
// 发送POST请求
HttpPost post = new HttpPost("http://example.com/api/register");
StringEntity entity = new StringEntity("username=myUser&password=mypassword");
entity.setContentType("application/x-www-form-urlencoded");
post.setEntity(entity);
response = httpClient.execute(post);
System.out.println("POST Response: " + response.getStatusLine());
} finally {
// 关闭连接池以释放资源
httpClient.close();
}
}
}
```
在这个例子中,我们首先创建了HttpClient实例,然后分别发送了一个GET请求和POST请求。记得处理响应并关闭连接。
阅读全文