java如何调用http接口
时间: 2023-05-12 22:06:24 浏览: 107
Java可以使用HttpURLConnection或者HttpClient来调用http接口。其中HttpURLConnection是Java自带的类,HttpClient是Apache的开源项目。以下是使用HttpURLConnection调用http接口的示例代码:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
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");
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();
}
}
}
```
以上代码使用GET方法请求一个http接口,并且设置了Accept头部为application/json。如果返回的状态码不是200,则抛出异常。最后输出接口返回的内容。
如果你想使用HttpClient来调用http接口,可以参考以下代码:
```java
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpClientExample {
public static void main(String[] args) {
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://example.com/api");
request.addHeader("Accept", "application/json");
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
以上代码使用HttpClient来调用http接口,并且设置了Accept头部为application/json。最后输出接口返回的内容。
阅读全文