使用HttpUtil工具传递headers参数
时间: 2023-11-23 22:06:33 浏览: 142
基于C++的网络调研工具(GUI)设计源码
可以用以下代码来传递headers参数:
```java
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class HttpUtil {
public static String sendGet(String urlString, Map<String, String> headers) throws IOException {
URL url = new URL(urlString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
con.setRequestProperty(entry.getKey(), entry.getValue());
}
}
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} else {
return "GET request failed with response code " + responseCode;
}
}
}
```
其中,headers参数在sendGet方法中传递,使用了for循环将其设置到HttpURLConnection的请求头部。
阅读全文