首页 > 其他分享 >OkHttp3发送http请求

OkHttp3发送http请求

时间:2023-09-14 18:02:24浏览次数:41  
标签:body http String url builder Request OkHttp3 发送 return

导入依赖

 <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.10.0</version>
        </dependency>

工具类

package com.ly.uitls;

import okhttp3.*;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @author : ly
 */
public class OkHttpClientUtil {

    private final static OkHttpClient okHttpClient = new OkHttpClient();

    /**
     * get请求
     *
     * @param url
     * @param headerMap
     * @return
     * @throws Exception
     */
    public static String get(String url, Map<String, String> headerMap) throws Exception {
        Request.Builder builder = new Request.Builder().url(url);
        if (!CollectionUtils.isEmpty(headerMap)) {
            headerMap.forEach((name, value) -> builder.addHeader(name, value));
        }
        Request request = builder.build();
        ResponseBody body = okHttpClient.newCall(request).execute().body();
        return body.string();
    }

    /**
     * @param url
     * @return
     */
    public static String getResult(String url) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            String string = response.body().string();
            return string;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * get 请求
     *
     * @param url
     * @param headerMap
     * @return
     * @throws Exception
     */
    public static String getData(String url, Map<String, String> headerMap) throws Exception {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request.Builder builder = new Request.Builder().url(url);
        if (!CollectionUtils.isEmpty(headerMap)) {
            headerMap.forEach((name, value) -> builder.addHeader(name, value));
        }
        Call call = okHttpClient.newCall(builder.build());
        try {
            Response response = call.execute();
            String string = response.body().string();
            return string;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * post 请求
     */
    public static String postData(String url, String json, Map<String, String> headerMap) throws Exception {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request.Builder builder = new Request.Builder().url(url);
        if (!CollectionUtils.isEmpty(headerMap)) {
            headerMap.forEach(builder::addHeader);
        }
        Request request = builder.post(requestBody).build();
        ResponseBody body = okHttpClient.newCall(request).execute().body();
        return resolver(body);
    }

    public static String postUrlencoded(String url, String json, Map<String, String> headerMap) throws Exception {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), json);
        Request.Builder builder = new Request.Builder().url(url);
        if (!CollectionUtils.isEmpty(headerMap)) {
            headerMap.forEach(builder::addHeader);
        }
        Request request = builder.post(requestBody).build();
        ResponseBody body = okHttpClient.newCall(request).execute().body();
        return resolver(body);
    }

    public static InputStream postDataByPdf(String url, String json, Map<String, String> headerMap) throws Exception {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), json);
        Request.Builder builder = new Request.Builder().url(url);
        if (!CollectionUtils.isEmpty(headerMap)) {
            headerMap.forEach(builder::addHeader);
        }
        Request request = builder.post(requestBody).build();
        ResponseBody body = okHttpClient.newCall(request).execute().body();
        return body.byteStream();
    }

    /**
     * put 请求
     *
     * @param url
     * @param reqbody
     * @param map
     * @return
     */

    public static String putData(String url, String reqbody, Map<String, String> map) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), reqbody);
        Request.Builder builder = new Request.Builder().url(url);
        if (!CollectionUtils.isEmpty(map)) {
            map.forEach((name, value) -> builder.addHeader(name, value));
        }
        Request request = builder.put(requestBody).build();
        try {
            ResponseBody body = okHttpClient.newCall(request).execute().body();
            return resolver(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * delete 请求
     *
     * @param url
     * @param reqbody
     * @param map
     * @return
     */
    public static String deleteData(String url, String reqbody, Map<String, String> map) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request.Builder builder = new Request.Builder().url(url);
        if (!CollectionUtils.isEmpty(map)) {
            map.forEach((name, value) -> builder.addHeader(name, value));
        }
        Call call = okHttpClient.newCall(builder.build());
        try {
            Response response = call.execute();
            String string = response.body().string();
            return string;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析返回值
     *
     * @param responseBody
     * @return
     */
    private static String resolver(ResponseBody responseBody) {
        InputStream is = null;
        String result = null;
        try {
            is = responseBody.byteStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            String body = null;
            StringBuilder sb = new StringBuilder();
            while ((body = br.readLine()) != null) {
                sb.append(body);
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}

标签:body,http,String,url,builder,Request,OkHttp3,发送,return
From: https://www.cnblogs.com/ybbit/p/17703080.html

相关文章

  • spring boot RestTemplate http请求
    RestTemplaterestTemplate=newRestTemplate();SimpleClientHttpRequestFactoryrequestFactory=newSimpleClientHttpRequestFactory();requestFactory.setConnectTimeout(5000);//设置连接超时时间为5秒requestFactory.setReadTimeout(5000);//设置读取超时时......
  • https nginx安装证书 ssl证书安装 nginx ssl
    ]#cd/etc/nginx/拷贝文件:#rz---上传ssl配置文件,keyandcrt添加文件:cd/usr/share/nginx/htmlrzcd/etc/nginx/conf.dtouchxxxkeji.confvimxxxkeji.conf加入:--server{listen443ssl;server_namewww.xxxkeji.com;......
  • 基于HTTP协议的客户端缓存
    提到缓存,一般都会想起redis、memcached等分布式缓存系统。虽然使用这些服务器端缓存速度能提升不少,但其实还是需要客户端下载这部分数据,目前在移动互联网领域,节省流量是很有必要的,因此工作中也就需要加入客户端缓存的相关技术。 怎么使用客户端缓存?1、用http报头中的last-modified......
  • Nginx神奇的499竟然不在HTTP响应码标准内?快来了解一下!
    1前言高性能的HTTP和反向代理服务器,Nginx用来:搭建WebServer作负载均衡供配置的日志字段丰富,从各类HTTP头部到内部性能数据都有Nginx的访问日志中,存在499状态码的日志。但常见4xx状态码只有400、401、403、404等,499并未在HTTPRFC文档。这499错误日志,在流量较大场景下,特别......
  • 核桃云监控:https://jk.htyun.net/
    今天给大家推荐一款非常好用的网站监测平台,也是我一直再用的,它就好比给自家的网站上雇了一个管家,它可以替我24小时不间断端的扫描网站,如果出现宕机,或者因为网络还是其他问题打不开时,系统会自动发送报警来提醒我,这样就节省了我的大部分时间,而我就不用时不时去自己去登录网站检查了,......
  • 计算机网络HTTP与TCP常见知识点思维导图
    本篇思维导图主要介绍了HTTP与TCP常见知识点,广度与深度兼具,希望对大家有帮助,需要xmind格式联系我,转发请备注来源,谢谢! ......
  • windows defender怎么关闭https://www.lingfenmao.com/it/2643.html
    工具/原料:       品牌型号:联想昭阳K4e-IML       系统版本:Windows10        关闭windowsdefender放火墙可使用组策略禁用和安全中心两种方法操作,以下为组策略禁用关闭的步骤说明:方法一:组策略禁用法1打开电脑Win+R键打开命令框......
  • 在dva.js里面发送异步action
    在dva.js的effects里面不能使用setTimeout,会报错。得使用redux-saga的delay才行(注:dva.js内置了redux-saga)。如下,这样才能延时。 ......
  • http请求头中的Range参数
    http请求头的Range参数是指分段请求字节数.当请求资源文件的时候,可以通过该参数指定获取资源的字节范围.这个字节范围是从0开始到左右闭合区间.例如:Range:bytes=500-999#表示获取资源文件第500个字节到第999个字节的数据.Range参数可以被用于多线程分段下载,断点续传等.......
  • SpringMVC报错:HTTP Status 405 - JSPs only permit GET POST or HEAD
    错误描述如果项目是运行在Tomcat8及以上版本,浏览器发出的PUT请求和DELETE请求可以被页面控制器(Controller)成功接收到,但是返回JSP页面则会报HTTP405的错误提示:"消息JSP只允许GET、POST或HEAD。Jasper还允许OPTIONS"。原因分析原因是Tomcat按照JCP规范(JSP......