java 调用http接口
时间: 2023-11-19 16:07:10 浏览: 29
Java可以使用多种方式调用HTTP接口,以下是其中两种常用的方法:
1. 使用JDK内置的HttpURLConnection类进行调用
```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 con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
```
2. 使用第三方库如Apache HttpClient进行调用
```java
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) {
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://example.com/api");
HttpResponse response = client.execute(request);
String responseString = EntityUtils.toString(response.getEntity());
System.out.println(responseString);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
```
以上两种方法都可以根据需要进行参数设置、鉴权等操作。