java http工具类
时间: 2023-06-30 12:09:21 浏览: 136
java工具类http
Java提供了很多http工具类,其中比较常用的是`HttpURLConnection`和`HttpClient`。
1. HttpURLConnection:
```java
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方式和超时时间
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
// 发送请求
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
// 读取响应流
InputStream inputStream = conn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder response = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
inputStream.close();
conn.disconnect();
return response.toString();
} else {
conn.disconnect();
return null;
}
```
2. HttpClient:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(urlStr);
// 设置请求参数
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setSocketTimeout(5000)
.build();
httpGet.setConfig(requestConfig);
// 发送请求
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
// 读取响应流
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
httpClient.close();
return result;
} else {
httpClient.close();
return null;
}
```
以上代码仅供参考,实际应用中需要根据具体需求进行适当的修改。
阅读全文