Java 使用 OkHttpClient 模拟 requests.get 请求
本文展示如何使用 Java 的 OkHttpClient 库模拟 Python requests 库的 get 请求,以实现如下代码逻辑:
requests.get(url=url, params={
'appId': '1234',
'cluster': 'default',
'notifications': [{'namespaceName': 'application', 'notificationId': -1}]
}, timeout=30)
以下是 Java 代码实现:
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class Example {
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient();
String url = "http://example.com";
String appId = "1234";
String cluster = "default";
String notifications = "[{"namespaceName": "application", "notificationId": -1}]";
String fullUrl = url + "?appId=" + appId + "&cluster=" + cluster + "¬ifications=" + notifications;
Request request = new Request.Builder()
.url(fullUrl)
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
}
注意: 在实际应用中,应该使用一些库来处理 JSON 数据,而不是手动拼接字符串。此处只是为了演示方便而简化了实现。
原文地址: https://www.cveoy.top/t/topic/oDxU 著作权归作者所有。请勿转载和采集!