java发送http get请求 {"code":"200","msg":"请求成功!","success":true,"data":null,"timestamp":"2024-01-13 09:55"}
时间: 2024-01-14 09:02:18 浏览: 39
以下是使用Java发送HTTP GET请求并获取响应的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://www.example.com/api");
// 创建HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
connection.setRequestMethod("GET");
// 获取响应代码
int responseCode = connection.getResponseCode();
// 判断响应代码是否为200
if (responseCode == HttpURLConnection.HTTP_OK) {
// 创建输入流读取响应内容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
// 读取响应内容
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出响应内容
System.out.println(response.toString());
} else {
System.out.println("请求失败,响应代码:" + responseCode);
}
// 关闭连接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```