HttpURLConnection 发送get 请求json
时间: 2024-05-03 18:23:05 浏览: 116
以下是使用HttpURLConnection发送GET请求并获取JSON响应的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUrlConnectionExample {
public static void main(String[] args) {
String url = "https://jsonplaceholder.typicode.com/todos/1";
try {
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在此示例中,我们使用HttpURLConnection打开URL并设置请求方法为GET。我们还设置了Accept标头以指示服务器返回JSON响应。如果响应代码不是200,则抛出运行时异常。最后,我们读取响应的输入流并打印JSON响应。
阅读全文