httpclient5发送post请求,和get请求,java代码详细示例,封装成方法
时间: 2024-03-06 12:46:11 浏览: 199
好的,以下是使用HttpClient5发送POST和GET请求的Java代码示例:
```java
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.StringEntity;
import java.io.IOException;
import java.net.URI;
public class HttpClientUtils {
/**
* 发送GET请求
*
* @param url 请求的URL
* @return 响应字符串
* @throws IOException
*/
public static String sendGetRequest(String url) throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(url);
ClassicHttpResponse response = httpClient.execute(httpGet);
return response.getEntity().toString();
}
}
/**
* 发送POST请求
*
* @param url 请求的URL
* @param params 请求参数(JSON格式)
* @return 响应字符串
* @throws IOException
*/
public static String sendPostRequest(String url, String params) throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(URI.create(url));
StringEntity requestEntity = new StringEntity(params, ContentType.APPLICATION_JSON);
httpPost.setEntity(requestEntity);
ClassicHttpResponse response = httpClient.execute(httpPost);
return response.getEntity().toString();
}
}
}
```
这里我们使用了Apache HttpClient5库来发送请求,通过封装成方法,可以方便地在其他地方调用。注意,在使用完CloseableHttpClient后,一定要关闭它,否则可能会导致连接泄露和资源浪费。在上面的示例中,我们使用了try-with-resources语法糖来自动关闭CloseableHttpClient。
阅读全文