java Accept", "application/json请求报文
时间: 2024-06-13 10:07:10 浏览: 92
以下是一个Java中发送"Accept", "application/json"请求报文的例子:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;import java.net.URL;
public class HttpExample {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/api/data");
HttpURLConnection conn = (HttpURLConnection) url.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();
}
}
}
```
这个例子中,我们使用了Java中的HttpURLConnection类来发送GET请求,并设置了请求头中的"Accept"为"application/json"。如果服务器返回的状态码不是200,就会抛出一个运行时异常。如果请求成功,我们就可以从服务器返回的输入流中读取响应数据并输出到控制台。
阅读全文