java的openapi对接例子
时间: 2023-10-23 08:13:51 浏览: 141
java API实例
4星 · 用户满意度95%
下面是一个简单的Java OpenAPI对接示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class OpenAPIDemo {
public static void main(String[] args) {
try {
String apiUrl = "https://api.example.com/getUserInfo?userId=123456";
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// Add request headers
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer " + "your_access_token_here");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Print response
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在此示例中,我们使用java.net包中的HttpURLConnection类建立与OpenAPI的连接,并设置请求方法(GET),请求头(Content-Type和Authorization),并读取响应数据。请注意,在此示例中,我们使用字符串插值将访问令牌添加到Authorization请求头中,但在实际应用程序中,您应该将访问令牌存储在安全的位置,并在需要时从该位置读取它。
阅读全文