java httpclient 工具类
时间: 2023-09-25 07:10:06 浏览: 110
httpclient 工具类
以下是一个 Java 中使用 HttpClient 的工具类示例:
```java
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
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;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
public static String get(String url) throws IOException {
// 创建 HttpClient 实例
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建 HttpGet 请求
HttpGet httpGet = new HttpGet(url);
// 执行请求
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
// 将响应实体转换为字符串
InputStream inputStream = entity.getContent();
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
return new String(bytes, StandardCharsets.UTF_8);
}
} finally {
// 关闭响应
response.close();
}
return null;
}
}
```
使用示例:
```java
public static void main(String[] args) throws IOException {
String response = HttpClientUtil.get("https://www.baidu.com");
System.out.println(response);
}
```
以上代码是一个简单的使用 HttpClient 发送 GET 请求的工具类示例,你可以根据自己的需求对其进行更改和扩展。
阅读全文