首页 > Web开发 > 详细

OKHttp使用笔记

时间:2019-08-08 11:59:06      阅读:100      评论:0      收藏:0      [点我收藏+]
  • 使用背景基于socket的java项目,需要对进行文件流操作,数据量较为巨大

 

  • boot中导入pom依赖

     <!--okhttp3-->
            <dependency>
                <groupId>com.squareup.okhttp3</groupId>
                <artifactId>okhttp</artifactId>
                <version>3.13.1</version>
            </dependency>

 

  • 编写工具类

    import okhttp3.*;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.util.CollectionUtils;
    
    import java.io.IOException;
    import java.util.Map;
    import java.util.Objects;
    
    /**
     * 利用OKHttp进行get和post的访问
     *
     */
    public class OKHttpUtil {
    
       static final Logger logger = LoggerFactory.getLogger(OKHttpUtil.class);
        /**
         * 发起get请求
         *
         * @param url
         * @return
         */
        public static String httpGet(String url) {
            String result = null;
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            try {
                Response response = client.newCall(request).execute();
                result = response.body().string();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    
        /**
         * 执行同步 Post请求
         * @param url
         * @param jsonStr
         * @param headers
         * @return
         * @throws IOException
         */
        public static Response httpPost(String url, String jsonStr, Map<String, String> headers) throws IOException {
            //构造请求体
            RequestBody requestBody = RequestBody.create(MediaType.parse("text/html;charset=utf-8"), jsonStr);
            //创建requestBody
            Request.Builder requestBuilder = new Request.Builder().url(url).post(requestBody);
            //构造请求头
            if(!CollectionUtils.isEmpty(headers)){
                for (Map.Entry<String, String> mapEntry : headers.entrySet()) {
                    // value不为空
                    if(!Objects.isNull(mapEntry.getValue())){
                        requestBuilder.addHeader(mapEntry.getKey(), String.valueOf(mapEntry.getValue()));
                    }
                }
            }
            //构建请求
            Request request = requestBuilder.build();
            //获取client
            OkHttpClient okHttpClient = new OkHttpClient();
            //执行
            Response response = okHttpClient.newCall(request).execute();
            return response;
        }
    
    
    }

OKHttp使用笔记

原文:https://www.cnblogs.com/21-Gram/p/11319524.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!