本篇文章详细介绍了在Java中使用HttpClient进行GET和POST请求的方法,并提供了完整的代码示例。适合需要了解或学习HTTP客户端编程的读者参考。
使用HttpClient的get和post方法实例的Java代码如下所示。这段代码完整且浅显易懂,并可以直接执行。这里基于httpclient4库来实现HTTP请求。
对于GET请求:
```java
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;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
// 创建一个默认的httpClient实例
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建GET请求
HttpGet httpget = new HttpGet(http://example.com);
System.out.println(Executing GET request + httpget.getRequestLine());
// 执行请求并获取响应实体
CloseableHttpResponse response = httpclient.execute(httpget);
try {
System.out.println(----------------------------------------);
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println(Response content length: + entity.getContentLength());
// 处理响应实体
// ...
}
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
```
对于POST请求:
```java
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
public class HttpClientExamplePost {
public static void main(String[] args) throws Exception {
// 创建一个默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建POST请求
HttpPost httppost = new HttpPost(http://example.com);
StringEntity input = new StringEntity({\param\:\value\});
input.setContentType(application/json);
httppost.setEntity(input);
System.out.println(Executing POST request + httppost.getRequestLine());
// 执行POST请求并获取响应实体
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println(----------------------------------------);
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println(Response content length: + entity.getContentLength());
// 处理响应实体
// ...
}
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
```
注意:上述代码中,`HttpGet`和`HttpPost`类用于分别发送GET请求和POST请求。同时使用了`StringEntity`来设置POST方法的实体内容,并且通过调用HTTP客户端实例的方法执行这些请求并获取响应。
以上就是基于httpclient4库实现的基本示例。