使用HttpUtli工具访问get请求并且设置请求头
时间: 2024-01-14 20:02:36 浏览: 59
好的,我可以回答您的问题。使用HttpUtil工具访问get请求,并设置请求头的代码如下:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class HttpUtil {
public static String sendGetRequest(String url, Map<String, String> headers) {
String result = "";
try {
URL connection = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) connection.openConnection();
httpURLConnection.setRequestMethod("GET");
if (headers != null && headers.size() != 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setReadTimeout(5000);
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == 200) {
result = readStream(httpURLConnection.getInputStream());
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private static String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
public static void main(String[] args) {
String url = "http://www.example.com";
Map<String, String> headers = new HashMap<>();
headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
String response = sendGetRequest(url, headers);
System.out.println(response);
}
}
```
您可以将上述代码复制到您的Java项目中,并按照自己的需求进行修改。记得引入必要的Java IO包和Java网络包。
阅读全文