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

本贴最后更新于 2217 天前,其中的信息可能已经水流花落

引入 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 com.yscall.kulaidian.constant.ConstantConfig;
import com.yscall.kulaidian.utils.EmptyUtils;
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);
    }
}
  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3186 引用 • 8212 回帖
  • OkHttp

    OkHttp 是一款 HTTP & HTTP/2 客户端库,专为 Android 和 Java 应用打造。

    16 引用 • 6 回帖 • 60 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...