Okhttp调用第三方系统接口
依赖 <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.9.1</version> </dependency>
import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class OkHttpExample { public static void main(String[] args) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://api.example.com/data") .build(); try (Response response = client.newCall(request).execute()) { System.out.println("Response: " + response.body().string()); } catch (Exception e) { e.printStackTrace(); } } }
-
创建一个
OkHttpClient
实例。 -
构建一个
RequestBody
对象,包含你要发送的数据。 -
创建一个
Request
对象,指定URL和RequestBody
。 -
使用
client.newCall(request).execute()
方法发送请求并获取响应。
以下是一个简单的示例,展示如何使用OkHttp发送一个HTTP POST请求:
标签:Request,request,接口,OkHttpClient,client,okhttp3,Okhttp,Response,随记 From: https://blog.csdn.net/weixin_64296810/article/details/139739016 import okhttp3.*; public class OkHttpPostExample { public static void main(String[] args) { OkHttpClient client = new OkHttpClient(); MediaType JSON = MediaType.parse("application/json; charset=utf-8"); String json = "{\"key\":\"value\"}"; RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url("https://api.example.com/data") .post(body) .build(); try (Response response = client.newCall(request).execute()) { System.out.println("Response: " + response.body().string()); } catch (Exception e) { e.printStackTrace(); } } }