java 调用http接口
时间: 2023-11-20 12:06:41 浏览: 37
Java 可以使用 HttpURLConnection 或者 HttpClient 来调用 HTTP 接口。这里简单介绍使用 HttpURLConnection 的方法。
示例代码:
```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) {
try {
URL url = new URL("http://example.com/api"); // 接口地址
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET"); // 请求方法为 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();
}
}
}
```
其中,需要修改的地方包括接口地址、请求方法、请求头等。如果是 POST 请求,需要设置请求体。