SLK的个人博客

  • 首页

  • 搜索
LRU Stack ThreadLocal Nacos RejectedExecutionHandler Executor RocketMQ ConcurrentHashMap CyclicBarrier Semaphore CountDownLatch canal Unsafe Atomic BlockingQueue AQS ReentrantLock Synchronized MESI Volatile JMM BufferPool Explain MySQL 常量池 Arthas JVM调优 三色标记 CMS ParNew 垃圾收集器 G1 Java Redis Android HTTPDNS DNS ioc 爬虫 seleniumhq 推荐引擎 Mahout IM Netty Vert.x HashMap 梯子 翻墙 V2ray Docker 搜索引擎 SpringBoot elasticsearch

基于Okhttp网络请求框架的封装

发表于 2018-10-10 | 分类于 Java | 0 | 阅读次数 252

引入Okhttp依赖

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.9.1</version>
    <scope>compile</scope>
</dependency>

网络请求

普通类型的网络请求

String url = "xxx.com/api/queryUserInfo";

Map<Object,Object> params = new HashMap<>();
Map<Object, Object> headers = new HashMap<>();
//添加请求体参数
params.put("userid","123456789");
//添加请求头参数
headers.put("token","41f05413-381c-4060-b8a1-acc6c5997164");
//GET 请求
String respone = okHttpPlugin.http(url, OkHttpPlugin.HttpMethod.GET, params, headers);
//POST 请求
String respone = okHttpPlugin.http(url, OkHttpPlugin.HttpMethod.POST, params, headers);

POST请求 提交JSON数据

String url = "xxx.com/api/queryUserInfo";

Map<Object,Object> body = new HashMap<>();
body.put("userid","123456789");

//序列化为JSON字符串
String bodyJson = GsonPlugin.toJson(body);

//提交请求
String respone = okHttpPlugin.http(url, bodyJson, OkHttpPlugin.MEDIA_TYPE_JSON);

下载文件 | 获取原始的Respone

String url = "xxx.com/api/queryUserInfo";

Map<Object,Object> params = new HashMap<>();
Map<Object, Object> headers = new HashMap<>();
//添加请求体参数
params.put("userid","123456789");
//添加请求头参数
headers.put("token","41f05413-381c-4060-b8a1-acc6c5997164");
//GET 请求
Response respone = okHttpPlugin.httpResponeBody(url, OkHttpPlugin.HttpMethod.GET, params, headers);
//POST 请求
Response respone = okHttpPlugin.httpResponeBody(url, OkHttpPlugin.HttpMethod.POST, params, headers);

//获取响应头
Headers responeHeaders = respone.headers();
        
//获取字符串 (如果响应格式是字符串的话  可以直接获取)
String string = respone.body().string();

//获取输入流
InputStream inputStream = respone.body().byteStream();
FileOutputStream outputStream = null;
try {
    //下载文件
    outputStream = new FileOutputStream(new File("D://123456.mp4"));
    byte by[] = new byte[1024];
    int len = -1;
    while ((len = inputStream.read(by))!=-1){
        outputStream.write(by,0,len);
    }
}catch (Exception e){
   e.printStackTrace();
}finally {
   if (respone!=null) {
       respone.close();
   }
   if (outputStream!=null) {
       try {
           outputStream.close();
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
}

OkHttp工具类

import okhttp3.*;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created by Pencilso on 2018/10/10/012.
 * 网络请求框架
 *
 * @author Pencilso
 */
@Component
public class OkHttpPlugin {
    public static final MediaType MEDIA_TYPE_XML = MediaType.parse("application/xml");
    public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json");

    private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(ConstantConfig.Reptilian.REPTILIAN_VIDEO_TIMEOUT, TimeUnit.MILLISECONDS)
            .readTimeout(ConstantConfig.Reptilian.REPTILIAN_VIDEO_TIMEOUT, TimeUnit.MILLISECONDS)
            .build();

    public enum HttpMethod {
        POST, GET
    }

    public Response httpResponeBody(String url, HttpMethod httpMethod) {
        return httpResponeBody(url, httpMethod, null);
    }

    public Response httpResponeBody(String url, HttpMethod httpMethod, Map<Object, Object> paramster) {
        return httpResponeBody(url, httpMethod, paramster, null);
    }

    public Response httpResponeBody(String url, HttpMethod httpMethod, Map<Object, Object> paramster, Map<Object, Object> header) {
        try {
            Request request = builderRequest(url, httpMethod, paramster, header);
            Response execute = okHttpClient.newCall(request).execute();
            return execute;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String http(String url, HttpMethod httpMethod) {
        return http(url, httpMethod, null, null);
    }

    public String http(String url, HttpMethod httpMethod, Map<Object, Object> paramster) {
        return http(url, httpMethod, paramster, null);
    }

    public String http(String url, HttpMethod httpMethod, Map<Object, Object> paramster, Map<Object, Object> header) {
        Response response = httpResponeBody(url, httpMethod, paramster, header);
        try {
            String string = response.body().string();
            return string;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return null;
    }


    public String http(String url, String context, MediaType mediaType, Map<Object, Object> header) {
        try {
            RequestBody body = RequestBody.create(mediaType, context);
            Request.Builder post = new Request.Builder()
                    .url(url)
                    .post(body);
            if (header != null && header.size() != 0) {
                Set<Map.Entry<Object, Object>> entries = header.entrySet();
                for (Map.Entry<Object, Object> entry : entries) {
                    String key = (String) entry.getKey();
                    String value = (String) entry.getValue();
                    if (EmptyUtils.isNull(key, value)) continue;
                    post.addHeader(key, value);
                }
            }
            Request build = post.build();
            Response execute = okHttpClient.newCall(build).execute();
            return execute.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String http(String url, String context, MediaType mediaType) {
        return http(url, context, mediaType, null);
    }

    private Request builderRequest(String url, HttpMethod httpMethod, Map<Object, Object> paramster, Map<Object, Object> header) {
        Request.Builder builder = new Request.Builder();
        if (httpMethod == HttpMethod.POST) {
            //POST 请求
            FormBody.Builder formBody = new FormBody.Builder();
            forEachMap(paramster, ((key, value) -> formBody.add(key, value)));
            builder.post(formBody.build()).url(url);
        } else if (httpMethod == HttpMethod.GET) {
            //GET 请求
            if (paramster != null && paramster.size() != 0) {
                StringBuffer sf = new StringBuffer("?");
                forEachMap(paramster, ((key, value) -> sf.append(key).append("=").append(value).append("&")));
                url += sf.toString();
            }
            builder.url(url);
        }
        //统一添加请求头
        forEachMap(header, (key, value) -> builder.addHeader(key, value));
        return builder.build();
    }

    private void forEachMap(Map<Object, Object> map, MapForInterface mapForInterface) {
        if (map != null && map.size() != 0) {
            Set<Map.Entry<Object, Object>> entries = map.entrySet();
            for (Map.Entry<Object, Object> entry : entries) {
                mapForInterface.result(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
            }
        }
    }


    interface MapForInterface {
        void result(String key, String value);
    }
}
# LRU # Stack # ThreadLocal # Nacos # RejectedExecutionHandler # Executor # RocketMQ # ConcurrentHashMap # CyclicBarrier # Semaphore # CountDownLatch # canal # Unsafe # Atomic # BlockingQueue # AQS # ReentrantLock # Synchronized # MESI # Volatile # JMM # BufferPool # Explain # MySQL # 常量池 # Arthas # JVM调优 # 三色标记 # CMS # ParNew # 垃圾收集器 # G1 # Java # Redis # Android # HTTPDNS # DNS # ioc # 爬虫 # seleniumhq # 推荐引擎 # Mahout # IM # Netty # Vert.x # HashMap # 梯子 # 翻墙 # V2ray # Docker # 搜索引擎 # SpringBoot # elasticsearch
基于selenium爬虫 抓取统计局省市县区域数据
Git 常用命令记录
  • 文章目录
  • 站点概览
宋龙宽

宋龙宽

87 日志
13 分类
53 标签
RSS
Github E-mail
Creative Commons
Links
  • 黑客派
  • Relyn
  • 张小妞的博客
  • ElasticSearch教程
© 2021 宋龙宽
由 Halo 强力驱动
|
主题 - NexT.Gemini v5.1.4