HttpURLConnection发送get请求body封装
时间: 2024-10-18 17:18:02 浏览: 16
http发送Get和Post请求工具类
当你需要通过HttpURLConnection在Java中发送GET请求,并且有数据需要包含在URL查询字符串部分(通常用于GET请求的简单参数传递),你可以这样做:
```java
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public String sendGetWithBody(URL url, String requestBody) throws Exception {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// 将请求体作为查询参数添加到URL
url = new URL(url.toString() + "?" + requestBody);
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
StringBuilder response = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
response.append(output);
}
br.close();
return response.toString();
}
// 使用示例
String requestBodyExample = "key1=value1&key2=value2";
URL requestUrl = new URL("http://example.com/api");
String result = sendGetWithBody(requestUrl, requestBodyExample);
```
在这个例子中,`requestBody`会被附加到URL的末尾,形成类似`http://example.com/api?key1=value1&key2=value2`的形式。
阅读全文