首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >OkHttp工具类

OkHttp工具类

原创
作者头像
JQ实验室
发布2025-07-30 14:25:58
发布2025-07-30 14:25:58
2060
举报
文章被收录于专栏:java基础教程java基础教程

OkHttpUtil

代码语言:xml
复制
<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>
代码语言:java
复制
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);

    }

}

OkHttpUtil

代码语言:xml
复制
<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>
代码语言:java
复制
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 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • OkHttpUtil
  • OkHttpUtil
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档