java调用http接口
时间: 2023-06-26 11:05:45 浏览: 60
Java 调用 HTTP 接口有多种方式,以下是其中两种常见的方式:
1. 使用 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 conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.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.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");
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String inputLine;
StringBuffer result = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
result.append(inputLine);
}
in.close();
System.out.println(result.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
```
无论使用哪种方式,都需要注意请求参数、请求头、响应状态码和响应内容等细节。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)