<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
</dependency>
<!-- 如果需要解析JSON响应,可以添加Gson库 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>import com.google.gson.Gson;
import okhttp3.*;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;
public class OkHttpUtil {
private static final OkHttpClient client = new OkHttpClient();
private static final Gson gson = new Gson();
// 发送GET请求并返回指定类型对象
public static <T> T sendGet(String url, Map<String, String> headers, Class<T> clazz,Type type) throws IOException {
Request.Builder requestBuilder = new Request.Builder().url(url);
// 添加请求头
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
}
Request request = requestBuilder.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
String responseBody = response.body().string();
if(type!=null){
return gson.fromJson(responseBody, type);
}
return gson.fromJson(responseBody, clazz);
}
}
// 发送POST请求并返回指定类型对象(带JSON请求体)
public static <T> T sendPostJson(String url, Object requestBodyObject, Map<String, String> headers, Class<T> clazz,Type type) throws IOException {
String jsonInputString = gson.toJson(requestBodyObject); // 将对象转换为JSON字符串
MediaType JSON = MediaType.get("application/json; charset=utf-8");
RequestBody body = RequestBody.create(jsonInputString, JSON);
Request.Builder requestBuilder = new Request.Builder().url(url).post(body);
// 添加请求头
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
}
Request request = requestBuilder.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
String responseBody = response.body().string();
if(type!=null){
return gson.fromJson(responseBody, type);
}
return gson.fromJson(responseBody, clazz);
}
}
public static void main(String[] args) {
// 示例:发送GET请求并返回对象
// String getUrl = "http://example.com/api/resource";
// Map<String, String> getHeaders = Map.of(
// "Authorization", "Bearer your_token_here",
// "Accept", "application/json"
// );
// MyResponse myGetResponse = sendGet(getUrl, getHeaders, MyResponse.class);
// System.out.println(myGetResponse);
//
// // 示例:发送POST请求并返回对象(带JSON请求体)
// String postUrl = "http://example.com/api/resource";
// MyRequest myRequest = new MyRequest("John", 30);
// Map<String, String> postHeaders = Map.of(
// "Authorization", "Bearer your_token_here",
// "Content-Type", "application/json"
// );
// MyResponse myPostResponse = sendPostJson(postUrl, myRequest, postHeaders, MyResponse.class);
// System.out.println(myPostResponse);
}
}<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
</dependency>
<!-- 如果需要解析JSON响应,可以添加Gson库 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>import com.google.gson.Gson;
import okhttp3.*;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;
public class OkHttpUtil {
private static final OkHttpClient client = new OkHttpClient();
private static final Gson gson = new Gson();
// 发送GET请求并返回指定类型对象
public static <T> T sendGet(String url, Map<String, String> headers, Class<T> clazz,Type type) throws IOException {
Request.Builder requestBuilder = new Request.Builder().url(url);
// 添加请求头
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
}
Request request = requestBuilder.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
String responseBody = response.body().string();
if(type!=null){
return gson.fromJson(responseBody, type);
}
return gson.fromJson(responseBody, clazz);
}
}
// 发送POST请求并返回指定类型对象(带JSON请求体)
public static <T> T sendPostJson(String url, Object requestBodyObject, Map<String, String> headers, Class<T> clazz,Type type) throws IOException {
String jsonInputString = gson.toJson(requestBodyObject); // 将对象转换为JSON字符串
MediaType JSON = MediaType.get("application/json; charset=utf-8");
RequestBody body = RequestBody.create(jsonInputString, JSON);
Request.Builder requestBuilder = new Request.Builder().url(url).post(body);
// 添加请求头
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
}
Request request = requestBuilder.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
String responseBody = response.body().string();
if(type!=null){
return gson.fromJson(responseBody, type);
}
return gson.fromJson(responseBody, clazz);
}
}
public static void main(String[] args) {
// 示例:发送GET请求并返回对象
// String getUrl = "http://example.com/api/resource";
// Map<String, String> getHeaders = Map.of(
// "Authorization", "Bearer your_token_here",
// "Accept", "application/json"
// );
// MyResponse myGetResponse = sendGet(getUrl, getHeaders, MyResponse.class);
// System.out.println(myGetResponse);
//
// // 示例:发送POST请求并返回对象(带JSON请求体)
// String postUrl = "http://example.com/api/resource";
// MyRequest myRequest = new MyRequest("John", 30);
// Map<String, String> postHeaders = Map.of(
// "Authorization", "Bearer your_token_here",
// "Content-Type", "application/json"
// );
// MyResponse myPostResponse = sendPostJson(postUrl, myRequest, postHeaders, MyResponse.class);
// System.out.println(myPostResponse);
}
}原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。