基于HttpClient的http请求工具类
时间: 2023-05-28 17:05:50 浏览: 196
http请求工具类
以下是基于HttpClient的http请求工具类的示例代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
public class HttpUtils {
public static String doGet(String url) {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream inputStream = httpEntity.getContent();
return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
```
该工具类提供了一个doGet方法,用于发送GET请求并返回响应内容。使用时,只需要传入请求的URL即可。
示例代码中使用了Apache HttpClient库,该库提供了丰富的API,可以方便地实现HTTP请求。在发送GET请求时,只需要创建一个HttpGet对象,并使用HttpClient.execute方法发送请求即可。获取响应内容时,可以从HttpResponse对象中获取HttpEntity对象,再从HttpEntity对象中获取InputStream对象,最后使用IOUtils.toString方法将InputStream对象转换为字符串即可。
阅读全文