模拟浏览器发送请求的java代码
时间: 2023-06-04 15:05:25 浏览: 225
抱歉,我可以回答您的问题。以下是模拟浏览器发送请求的Java代码示例:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpClientExample {
public static void main(String[] args) {
HttpURLConnection connection = null;
try {
// 创建URL
URL url = new URL("http://example.com");
// 打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置请求参数
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
// 发送请求
int responseCode = connection.getResponseCode();
// 读取响应
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出响应
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
```
请注意,这只是一个示例,实际应用中需要根据具体需求进行修改。
阅读全文