阅读量:1
在Java中发送GET请求并传递header参数,可以使用java.net.HttpURLConnection
类。下面是一个示例代码:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class Main { public static void main(String[] args) { try { // 创建URL对象 URL url = new URL("http://example.com/api?param1=value1¶m2=value2"); // 打开连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法为GET connection.setRequestMethod("GET"); // 设置header参数 connection.setRequestProperty("Header1", "Value1"); connection.setRequestProperty("Header2", "Value2"); // 获取响应代码 int responseCode = connection.getResponseCode(); // 读取响应内容 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { response.append(line); } bufferedReader.close(); // 打印响应内容 System.out.println(response.toString()); // 关闭连接 connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } }
在上述代码中,通过setRequestProperty
方法设置了header参数,然后通过getInputStream
方法获取响应内容。注意,需要将http://example.com/api?param1=value1¶m2=value2
替换为实际的请求URL,并根据需要设置自定义的header参数。