Java请求Http接口OkHttp超详细讲解(附带工具类)

 更新时间:2024年02月19日 08:24:25   作者:苍煜  
这篇文章主要给大家介绍了关于Java请求Http接口OkHttp超详细讲解的相关资料,OkHttp是一款优秀的HTTP客户端框架,文中通过代码示例介绍的非常详细,需要的朋友可以参考下

简介:

OkHttp是一个默认有效的HTTP客户端,有效地执行HTTP可以加快您的负载并节省带宽,如果您的服务有多个IP地址,如果第一次连接失败,OkHttp将尝试备用地址。这对于IPv4 + IPv6和冗余数据中心中托管的服务是必需的。OkHttp启动具有现代TLS功能(SNI,ALPN)的新连接,并在握手失败时回退到TLS 1.0,OkHttp支持Android 2.3及更高版本。对于Java,最低要求是1.7。

操作步骤:

1、创建OkhttpClient。

2、mClient执行newCall将Request转化成一个Call。

3、最后call执行excute同步执行,enqueue异步执行。

4、Request主要通过Request.Builder来构建。

5、缓存。

6、取消请求。

导包

<!--okhttp3-->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>

GET请求

get无参

/**
     * 以get方式调用第三方接口
     * @param url
     */
    public static void doGet1(String url) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求,可以不写
                .build();
        Response response = okHttpClient.newCall(request).execute();
        String string = response.body().string();
        System.out.println(string);

    }

get有参

public static void doGet2(String url, Map<String, Object> paramMap) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request.Builder requestbuilder = new Request.Builder()
               .get();//默认就是GET请求,可以不写
        
        StringBuilder urlbuilder = new StringBuilder(url);
        if (Objects.nonNull(paramMap)) {
            urlbuilder.append("?");
            paramMap.forEach((key, value) -> {
                try {
                    urlbuilder.append(URLEncoder.encode(key, "utf-8")).append("=").append(URLEncoder.encode((String) value, "utf-8")).append("&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            });
            urlbuilder.deleteCharAt(urlbuilder.length() - 1);
        }

        Request request = requestbuilder.url(urlbuilder.toString()).build();
        Response response = okHttpClient.newCall(request).execute();
        String string = response.body().string();
        System.out.println(string);

    }

get带参数和请求头

  /**
     * 以get方式调用第三方接口
     * @param url
     */
    public static void doGet3(String url, Map<String, Object> paramMap,Map<String, String> heardMap) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request.Builder requestbuilder = new Request.Builder()
                .get();//默认就是GET请求,可以不写

        //增加参数
        StringBuilder urlbuilder = new StringBuilder(url);
        if (Objects.nonNull(paramMap)) {
            urlbuilder.append("?");
            paramMap.forEach((key, value) -> {
                try {
                    urlbuilder.append(URLEncoder.encode(key, "utf-8")).append("=").append(URLEncoder.encode((String) value, "utf-8")).append("&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            });
            urlbuilder.deleteCharAt(urlbuilder.length() - 1);
        }
        //增加请求头
        Request.Builder heardBuilder = requestbuilder.url(urlbuilder.toString());
        for (Map.Entry<String, String> stringObjectEntry : heardMap.entrySet()) {
            heardBuilder.addHeader(stringObjectEntry.getKey(),stringObjectEntry.getValue());
        }

        Request request = heardBuilder.build();
        Response response = okHttpClient.newCall(request).execute();
        System.out.println(response.body().string());
        System.out.println(response.message());
        System.out.println(response.code());

    }

get请求 换种方式获取结果

/**
     * 以get方式调用第三方接口
     * @param url
     */
    public static void doGet(String url,Map<String, Object> paramMap,Map<String, String> heardMap) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request.Builder requestbuilder = new Request.Builder()
                .get();//默认就是GET请求,可以不写

        //增加参数
        StringBuilder urlbuilder = new StringBuilder(url);
        if (Objects.nonNull(paramMap)) {
            urlbuilder.append("?");
            paramMap.forEach((key, value) -> {
                try {
                    urlbuilder.append(URLEncoder.encode(key, "utf-8")).append("=").append(URLEncoder.encode((String) value, "utf-8")).append("&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            });
            urlbuilder.deleteCharAt(urlbuilder.length() - 1);
        }
        //增加请求头
        Request.Builder heardBuilder = requestbuilder.url(urlbuilder.toString());
        for (Map.Entry<String, String> stringObjectEntry : heardMap.entrySet()) {
            heardBuilder.addHeader(stringObjectEntry.getKey(),stringObjectEntry.getValue());
        }

        Request request = heardBuilder.build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println( "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println(response.body().string());
                System.out.println(response.message());
                System.out.println(response.code());
            }
        });
    }

POST请求

post-json传参

 /**
     * post请求
     * @param url
     * @param json
     */
    public static void doPost(String url, String json, Map<String, String> heardMap) throws IOException {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        String requestBody = json;
        Request.Builder requestbuilder = new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType, requestBody));
        //增加请求头
        for (Map.Entry<String, String> stringObjectEntry : heardMap.entrySet()) {
            requestbuilder.addHeader(stringObjectEntry.getKey(), stringObjectEntry.getValue());
        }

        Request request = requestbuilder.build();
        OkHttpClient okHttpClient = new OkHttpClient();
        Response response = okHttpClient.newCall(request).execute();
        System.out.println(response.body().string());
        System.out.println(response.message());
        System.out.println(response.code());
    }

post-params传参

 /**
     * post请求
     * @param url
     * @param json
     */
    public static void doPost(String url, String json, Map<String, String> heardMap) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        String requestBody = json;
        Request.Builder requestbuilder = new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType, requestBody));
        //增加请求头
        for (Map.Entry<String, String> stringObjectEntry : heardMap.entrySet()) {
            requestbuilder.addHeader(stringObjectEntry.getKey(), stringObjectEntry.getValue());
        }

        Request request = requestbuilder.build();
        OkHttpClient okHttpClient = new OkHttpClient();
        Response response = okHttpClient.newCall(request).execute();
        System.out.println(response.body().string());
        System.out.println(response.message());
        System.out.println(response.code());
    }
 /**
     * post请求
     * @param url
     * @param paramMap
     */
    public static void doPost1(String url, Map<String, Object> paramMap,Map<String,String> heardMap) throws IOException {
        FormBody.Builder formBody = new FormBody.Builder();
        if (Objects.nonNull(paramMap)) {
            paramMap.forEach((x, y) -> formBody.add(x, (String) y));
        }
        RequestBody requestBody = formBody.build();
        Request.Builder requestbuilder = new Request.Builder()
                .url(url)
                .post(requestBody);
        //增加请求头
        for (Map.Entry<String, String> stringObjectEntry : heardMap.entrySet()) {
            requestbuilder.addHeader(stringObjectEntry.getKey(), stringObjectEntry.getValue());
        }

        Request request = requestbuilder.build();
        OkHttpClient okHttpClient = new OkHttpClient();
        Response response = okHttpClient.newCall(request).execute();
        System.out.println(response.body().string());
        System.out.println(response.message());
        System.out.println(response.code());
    }

post-表单传参-上传文件

达到类似效果

 public static void doPost2(String url,File file) throws IOException {
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("id", "111")
                .addFormDataPart("content", "{\"do_layout\":1}")
                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("text/plain"), file))
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("x-tilake-app-key", "")
                .addHeader("x-tilake-ca-timestamp", "")
                .addHeader("x-tilake-ca-signature", "")
                .addHeader("Content-Type", body.contentType().toString())
                .addHeader("Accept", "*/*")
                .build();

        try {
            Response response = client.newCall(request).execute();
            System.out.println(response.body().string());
            System.out.println(response.message());
            System.out.println(response.code());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

提供一个工具类,可以直接使用

package com.example.httpdemo.okhttp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Slf4j
public class OkHttpUtil {

    public static final String MEDIA_TYPE_JSON = "application/json; charset=utf-8";

    private OkHttpUtil() {
    }

    /**
     * 获取默认的OkHttpClient
     * @return
     */
    public static OkHttpClient getOkHttpClient() {
        return getOkHttpClient(60, 60, 60);
    }

    public static OkHttpClient getOkHttpClient(int connectTimeout, int readTimeOut, int writeTimeOut) {
        OkHttpClient.Builder builder = new okhttp3.OkHttpClient().newBuilder();
        builder.connectTimeout(connectTimeout, TimeUnit.SECONDS);
        builder.readTimeout(readTimeOut, TimeUnit.SECONDS);
        builder.writeTimeout(writeTimeOut, TimeUnit.SECONDS);
        return builder.build();
    }

    /**
     * get请求
     * @param okHttpClient
     * @param url
     * @param headers header参数
     * @return
     */
    public static String get(OkHttpClient okHttpClient, String url, Headers headers) {
        log.info("okHttpClient get url:{}.", url);
        Request request = new Request.Builder().url(url).headers(headers).get().build();

        String responseData = request(okHttpClient, url, request);
        log.info("okHttpClient get url:{},request responseData====> {}", url, responseData);
        return responseData;
    }

    public static String get(OkHttpClient okHttpClient, String url) {
        Headers headers = new Headers.Builder().build();
        return get( okHttpClient, url, headers);
    }

    /**
     * GET请求。使用默认的 okHttpClient 和 headers
     * @param url
     * @return
     */
    public static String get(String url) {
        OkHttpClient okHttpClient = getOkHttpClient();
        Headers headers = new Headers.Builder().build();
        return get( okHttpClient, url, headers);
    }

    /**
     * post请求,获取响应结果
     *
     * @param okHttpClient
     * @param url
     * @param bodyJson
     * @param headers
     * @return
     */
    public static String post(OkHttpClient okHttpClient, String url, JSONObject bodyJson, Headers headers) {
        log.info("okHttpClient post url:{}, body====> {}", url, bodyJson);
        MediaType mediaTypeJson = MediaType.parse(MEDIA_TYPE_JSON);
        RequestBody requestBody = RequestBody.create(mediaTypeJson, JSON.toJSONString(bodyJson));
        Request request = new Request.Builder().url(url).headers(headers).post(requestBody).build();

        String responseData = request(okHttpClient, url, request);
        log.info("okHttpClient post url:{},post responseData====> {}", url, responseData);
        return responseData;
    }

    public static String post(OkHttpClient okHttpClient, String url, JSONObject bodyJson) {
        Headers headers = new Headers.Builder().build();
        return post( okHttpClient,  url,  bodyJson, headers);
    }

    /**
     * post请求。使用默认的 okHttpClient 和 headers
     * @param url
     * @param bodyJson
     * @return
     */
    public static String post( String url, JSONObject bodyJson) {
        //使用默认的 okHttpClient
        OkHttpClient okHttpClient = getOkHttpClient();
        Headers headers = new Headers.Builder().build();
        //如果需要自定义 okHttpClient或headers传参,可以调用以下方法
        return post( okHttpClient,  url,  bodyJson, headers);
    }

    /**
     * 获取响应结果
     *
     * @param okHttpClient
     * @param url
     * @param request
     * @return
     */
    public static String request(OkHttpClient okHttpClient, String url, Request request) {
        String responseData = "";
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (response != null && response.body() != null) {
                return response.body().string();
            }
        } catch (Exception e) {
            log.error("okHttpClient getResponse error.url:{}", url, e);
        }

        return responseData;
    }

    /**
     * 上传文件
     *
     * @param okHttpClient  okHttp客户端
     * @param url 上传文件的url
     * @param fileKey       文件对应的key
     * @param formDataJson  form-data参数
     * @param headers
     * @param file
     * @return
     */
    public static String uploadFile(OkHttpClient okHttpClient, String url,
                                     String fileKey, File file, JSONObject formDataJson, Headers headers) {
        log.info("uploadFile url:{}, uploadFile formDataJson====> {}", url, formDataJson);
        // 支持传文件的同时,传参数。
        MultipartBody requestBody = getMultipartBody(fileKey, file,  formDataJson);

        // 构建request请求体
        Request request = new Request.Builder().url(url).headers(headers).post(requestBody).build();

        String responseData = request(okHttpClient, url, request);

        // 会在本地产生临时文件,用完后需要删除
        if (file.exists()) {
            file.delete();
        }
        return responseData;

    }

    /**
     * 上传文件
     * @param url
     * @param fileKey form-data文件对应的key
     * @param multipartFile 文件上传对应的 multipartFile
     * @param formDataJson form-data参数
     * @return
     */
    public static String uploadFile(String url,
                                    String fileKey, MultipartFile multipartFile, JSONObject formDataJson) {
        //使用默认的okHttpClient
        OkHttpClient okHttpClient = getOkHttpClient();
        Headers headers = new Headers.Builder().build();
        return uploadFile(okHttpClient, url, fileKey, getFile(multipartFile), formDataJson, headers);
    }

    public static String uploadFile(OkHttpClient okHttpClient, String url,
                                    String fileKey, File file, JSONObject formDataJson) {
        Headers headers = new Headers.Builder().build();
        return uploadFile(okHttpClient, url,  fileKey, file, formDataJson, headers);
    }

    /**
     * 上传文件
     * 使用默认的okHttpClient
     *
     * @param url
     * @param fileKey form-data文件对应的key
     * @param file 文件
     * @param formDataJson form-data参数
     * @return
     */
    public static String uploadFile(String url,
                                    String fileKey, File file, JSONObject formDataJson) {
        //使用默认的okHttpClient
        OkHttpClient okHttpClient = getOkHttpClient();
        Headers headers = new Headers.Builder().build();
        return uploadFile(okHttpClient, url, fileKey, file, formDataJson, headers);
    }

    /**
     * 上传文件用。构建form-data 参数
     *
     * @param fileKey       文件对应的key
     * @param file          文件
     * @param formDataJson  form-data参数
     * @return
     */
    public static MultipartBody getMultipartBody(String fileKey, File file, JSONObject formDataJson) {
        RequestBody fileBody = RequestBody.create(MultipartBody.FORM, file);

        MultipartBody.Builder bodyBuilder = new MultipartBody.Builder();
        // 设置传参为form-data格式
        bodyBuilder.setType(MultipartBody.FORM);
        bodyBuilder.addFormDataPart(fileKey, file.getName(), fileBody);
        // 添加 form-data参数
        for (Map.Entry<String, Object> entry : formDataJson.entrySet()) {
            //参数通过 bodyBuilder.addFormDataPart(key, value) 添加
            bodyBuilder.addFormDataPart(entry.getKey(), Objects.toString(entry.getValue(),""));
        }
        return bodyBuilder.build();
    }

    /**
     * 获取文件
     * @param multipartFile
     * @return
     */
    public static File getFile(MultipartFile multipartFile) {
        File file = new File(Objects.requireNonNull(multipartFile.getOriginalFilename()));
        try {
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
        } catch (IOException e) {
            log.error("copyInputStreamToFile error.", e);
        }
        return file;
    }

}

总结 

到此这篇关于Java请求Http接口OkHttp的文章就介绍到这了,更多相关Java请求Http接口OkHttp内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java实现数据库连接池的方法

    Java实现数据库连接池的方法

    这篇文章主要介绍了Java实现数据库连接池的方法,涉及java数据库连接池的创建、连接、刷新、关闭及状态获取的常用技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-07-07
  • 详解JVM虚拟机的类加载机制

    详解JVM虚拟机的类加载机制

    这篇文章主要介绍了详解JVM虚拟机的类加载机制,虚拟机把描述类的数据从 Class 文件加载到内存,并对数据进行校验、转换解析和初始化,最终形成可以被虚拟机直接使用的 Java 类型,这就是虚拟机的类加载机制,需要的朋友可以参考下
    2023-08-08
  • Java集合框架之WeakHashMap详解

    Java集合框架之WeakHashMap详解

    这篇文章主要介绍了Java集合框架之WeakHashMap详解,在 WeakHashMap 中,当某个键不再正常使用时,会被从WeakHashMap中被自动移除,更精确地说,对于一个给定的键,其映射的存在并不阻止垃圾回收器对该键的丢弃,这就使该键成为可终止的,需要的朋友可以参考下
    2023-09-09
  • Java经典快排思想以及快排的改进讲解

    Java经典快排思想以及快排的改进讲解

    今天小编就为大家分享一篇关于Java经典快排思想以及快排的改进讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01
  • centos7如何通过systemctl启动springboot服务代替java -jar方式启动

    centos7如何通过systemctl启动springboot服务代替java -jar方式启动

    这篇文章主要介绍了centos7如何通过systemctl启动springboot服务代替java -jar方式启动,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2024-01-01
  • 详解Java中Quartz的简单使用

    详解Java中Quartz的简单使用

    Quartz 是一个开源的作业调度框架,它完全由 Java 写成,并设计用于 J2SE 和 J2EE 应用中。这篇文章主要通过示例和大家讲讲Quartz的简单使用,需要的可以参考一下
    2023-04-04
  • javaWeb连接数据库实现简单登陆注册功能的全过程

    javaWeb连接数据库实现简单登陆注册功能的全过程

    初学javaWeb,老师留下一小作业,用JAVA实现与服务器端交互,实现登录和注册功能,下面这篇文章主要给大家介绍了关于javaWeb连接数据库实现简单登陆注册功能的相关资料,需要的朋友可以参考下
    2022-06-06
  • springboot项目整合druid数据库连接池的实现

    springboot项目整合druid数据库连接池的实现

    这篇文章主要介绍了springboot项目整合druid数据库连接池的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-04-04
  • java 开发使用字符串和数字的性能分析

    java 开发使用字符串和数字的性能分析

    这篇文章主要介绍了java 开发使用字符串和数字的性能分析的相关资料,需要的朋友可以参考下
    2017-07-07
  • 一键打包压缩,Java项目变身JAR

    一键打包压缩,Java项目变身JAR

    想要一键打包Java项目生成JAR文件并进行压缩?本指南将带你轻松驾驭这项看似复杂的任务,让我们一起揭开神秘的面纱,轻松打包,高效出发!
    2023-12-12

最新评论