java web如何調(diào)用接口

在Java Web中調(diào)用接口主要有以下幾種方式: 1. 使用`HttpURLConnection`Java內(nèi)置的`HttpURLConnection`類可以用來(lái)發(fā)送HT...
在Java Web中調(diào)用接口主要有以下幾種方式:
1. 使用`HttpURLConnection`
Java內(nèi)置的`HttpURLConnection`類可以用來(lái)發(fā)送HTTP請(qǐng)求。
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUrlConnectionExample {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/api/data");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
本文鏈接:http://www.resource-tj.com/bian/340895.html