用java模拟一个http请求
时间: 2024-05-09 14:19:31 浏览: 73
模拟https请求
以下是一个简单的Java程序,用于模拟HTTP GET请求:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetRequest {
public static void main(String[] args) throws Exception {
String url = "https://www.example.com";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
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.toString());
}
}
```
这个程序使用Java的java.net包中的HttpURLConnection类来建立HTTP GET请求。程序将请求发送到指定的URL,并读取响应。在这个例子中,程序将响应输出到控制台。
阅读全文