How to call interfaces from other projects in Java?
To invoke the interface of another project, you can use a HTTP client library in Java to send HTTP requests and receive responses. Here is a simple example code demonstrating how to use HttpURLConnection in Java to call the interface of another project:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ApiClient {
public static void main(String[] args) {
try {
URL url = new URL("http://api.example.com/some-endpoint");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// 设置请求头
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer your_access_token");
// 发起请求
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} else {
System.out.println("Failed to call API. Response code: " + responseCode);
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
In the example above, we used HttpURLConnection to create a GET request, set some request headers (such as Content-Type and Authorization), checked the response code, and printed the response content.
Please note that in actual use, it may be necessary to make appropriate settings and handling based on the requirements of the interface, such as processing JSON data responses or sending POST requests. Additionally, we can also use third-party libraries, such as Apache HttpClient or OkHttp, to simplify the handling of HTTP requests.