java中怎样使用HttpHelper
时间: 2023-08-31 19:09:28 浏览: 54
Java中可以使用HttpURLConnection或者HttpClient库来发送HTTP请求和接收HTTP响应。
使用HttpURLConnection发送HTTP请求:
```java
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.BufferedInputStream;
import java.io.InputStream;
public class HttpHelper {
public static String sendGetRequest(String urlString) throws Exception {
URL url = new URL(urlString); // 创建URL对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 建立HTTP连接
conn.setRequestMethod("GET"); // 设置请求方法为GET
conn.connect(); // 发送请求
int responseCode = conn.getResponseCode(); // 获取HTTP响应码
if (responseCode != 200) { // 处理HTTP错误
throw new Exception("HTTP error code: " + responseCode);
}
InputStream in = new BufferedInputStream(conn.getInputStream()); // 获取HTTP响应数据流
String response = streamToString(in); // 将HTTP响应数据流转化为字符串
return response; // 返回HTTP响应字符串
}
private static String streamToString(InputStream in) throws Exception {
StringBuilder sb = new StringBuilder(); // 创建StringBuilder对象
byte[] buffer = new byte[1024]; // 创建一个长度为1024的byte数组
int len = -1;
while ((len = in.read(buffer)) != -1) { // 从HTTP响应数据流中读取数据,直到读到末尾
String s = new String(buffer, 0, len, "UTF-8"); // 将读到的数据转化为字符串
sb.append(s); // 使用StringBuilder对象拼接字符串
}
return sb.toString(); // 返回拼接好的字符串
}
}
```
使用HttpClient发送HTTP请求:
```java
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpHelper {
public static String sendGetRequest(String urlString) throws Exception {
HttpClient client = HttpClientBuilder.create().build(); // 创建HttpClient对象
HttpGet request = new HttpGet(urlString); // 创建HttpGet对象
HttpResponse response = client.execute(request); // 使用HttpClient对象发送HTTP请求,并获取HttpResponse对象
int statusCode = response.getStatusLine().getStatusCode(); // 获取HTTP响应码
if (statusCode != 200) { // 处理HTTP错误
throw new Exception("HTTP error code: " + statusCode);
}
String responseString = EntityUtils.toString(response.getEntity(), "UTF-8"); // 将HTTP响应数据转化为字符串
return responseString; // 返回HTTP响应字符串
}
}
```
以上代码只是简单的示例,实际使用中应该加入错误处理和异常处理等内容。