我的编程空间,编程开发者的网络收藏夹
学习永远不晚

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

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

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

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

操作步骤:

创建OkhttpClient。

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

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

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

缓存。

取消请求。

导包

        <dependency>            <groupId>com.squareup.okhttp3groupId>            <artifactId>okhttpartifactId>            <version>4.9.1version>        dependency>        <dependency>            <groupId>commons-iogroupId>            <artifactId>commons-ioartifactId>            <version>2.5version>        dependency>

GET请求

get无参

    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带参数和请求头

      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请求 换种方式获取结果

    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传参

     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传参

     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());    }
     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", "*    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();    }        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);    }        public static String get(String url) {        OkHttpClient okHttpClient = getOkHttpClient();        Headers headers = new Headers.Builder().build();        return get( okHttpClient, url, headers);    }        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);    }        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);    }        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;    }        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;    }        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);    }        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);    }        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();    }        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;    }}

来源地址:https://blog.csdn.net/qq_41694906/article/details/132345812

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

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

下载Word文档到电脑,方便收藏和打印~

下载Word文档

编程热搜

  • Python 学习之路 - Python
    一、安装Python34Windows在Python官网(https://www.python.org/downloads/)下载安装包并安装。Python的默认安装路径是:C:\Python34配置环境变量:【右键计算机】--》【属性】-
    Python 学习之路 - Python
  • chatgpt的中文全称是什么
    chatgpt的中文全称是生成型预训练变换模型。ChatGPT是什么ChatGPT是美国人工智能研究实验室OpenAI开发的一种全新聊天机器人模型,它能够通过学习和理解人类的语言来进行对话,还能根据聊天的上下文进行互动,并协助人类完成一系列
    chatgpt的中文全称是什么
  • C/C++中extern函数使用详解
  • C/C++可变参数的使用
    可变参数的使用方法远远不止以下几种,不过在C,C++中使用可变参数时要小心,在使用printf()等函数时传入的参数个数一定不能比前面的格式化字符串中的’%’符号个数少,否则会产生访问越界,运气不好的话还会导致程序崩溃
    C/C++可变参数的使用
  • css样式文件该放在哪里
  • php中数组下标必须是连续的吗
  • Python 3 教程
    Python 3 教程 Python 的 3.0 版本,常被称为 Python 3000,或简称 Py3k。相对于 Python 的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0 在设计的时候没有考虑向下兼容。 Python
    Python 3 教程
  • Python pip包管理
    一、前言    在Python中, 安装第三方模块是通过 setuptools 这个工具完成的。 Python有两个封装了 setuptools的包管理工具: easy_install  和  pip , 目前官方推荐使用 pip。    
    Python pip包管理
  • ubuntu如何重新编译内核
  • 改善Java代码之慎用java动态编译

目录