java 调用http接口
时间: 2023-11-20 17:05:43 浏览: 17
Java可以通过多种方式调用HTTP接口,这里提供一种使用Java原生库`HttpURLConnection`的方法。
```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 url = new URL("http://www.example.com/api");
// 打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法和请求头
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
// 发送请求
conn.connect();
// 获取响应码
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 获取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} else {
System.out.println("HTTP request failed, response code: " + responseCode);
}
// 断开连接
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的例子中,我们使用了`HttpURLConnection`类打开了一个HTTP连接,并设置了请求的方法和请求头。然后我们将连接发送出去,并获取响应码。如果响应码是`HTTP_OK`,则说明请求成功,我们可以通过`getInputStream`方法获取响应内容。最后不要忘记关闭连接。