java代码 发送http get请求带参数
时间: 2023-07-31 08:04:09 浏览: 124
可以使用 HttpURLConnection 类来发送 HTTP GET 请求,以下是一个带参数的示例代码:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpGetWithParamsExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api";
String params = "key1=value1&key2=value2";
URL obj = new URL(url + "?" + params);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("Sending GET request to URL: " + url);
System.out.println("Params: " + params);
System.out.println("Response Code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response body: " + response.toString());
}
}
```
在上面的示例中,我们使用 URL 和 HttpURLConnection 类来发送带参数的 HTTP GET 请求。请注意,我们将参数附加到 URL 后面,并使用 setRequestMethod() 方法将请求类型设置为 GET。我们还设置了 User-Agent 标头,以模拟一个真实的浏览器。最后,我们读取响应主体并将其打印到控制台。
阅读全文