java模拟httpget请求
时间: 2023-10-02 17:09:33 浏览: 90
以下是Java模拟HttpGet请求的示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetExample {
public static void main(String[] args) throws IOException {
String url = "https://www.example.com";
HttpURLConnection connection = null;
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
```
这个示例代码通过创建一个`HttpURLConnection`对象,来模拟GET请求。可以通过设置请求的URL和请求方法,然后获取响应结果。
阅读全文