java前端调用后端接口
时间: 2023-08-17 09:39:07 浏览: 102
java代码调用接口
3星 · 编辑精心推荐
Java前端调用后端接口可以使用Java的HttpURLConnection或者Apache HttpClient等工具。
下面以HttpURLConnection为例,示范如何使用Java代码调用后端接口:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpUrlConnectionDemo {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:8080/api/getUserInfo?id=123"); // 接口地址
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()), StandardCharsets.UTF_8));
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();
}
}
}
```
以上代码中,我们使用HttpURLConnection向 http://localhost:8080/api/getUserInfo 接口发送了一个GET请求,并且设置了请求头Accept为application/json。如果请求成功,我们就可以通过conn.getInputStream()获取响应结果,然后进行处理。
阅读全文