HttpUtils.sendGet
时间: 2023-09-23 20:05:32 浏览: 94
您可以使用以下代码来发送 GET 请求:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUtils {
public static String sendGet(String url) throws Exception {
// 创建 URL 对象
URL obj = new URL(url);
// 创建 HttpURLConnection 对象
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为 GET
con.setRequestMethod("GET");
// 获取响应码
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} else {
throw new Exception("GET request failed. Response Code: " + responseCode);
}
}
}
```
您可以使用 `HttpUtils.sendGet(url)` 来发送 GET 请求,其中 `url` 是您要请求的 URL。
阅读全文