okhttp简单封装

之前一直用的是httpclient,今天okhttp简单封装了一下,主要有三个方法

  1. 发送get请求
  2. 发送post请求,请求体是json字符串
  3. 发送post请求,可以什么都不传,可以是简单的表单提交,也可以是带文件上传的表单提交

这里写图片描述

post上传文件需要的实体

/**
 * form表单提交文件上传的文件对象
 *
 * @author chenggaowei Created on 2018-05-09 23:30
 **/
@Getter
@Setter
@ToString
public class PostFile {

  /**
   * 要上传的文件
   */
  private File file;
  /**
   * 表单对应的名称
   */
  private String formName;

  public PostFile(File file, String formName) {
    this.file = file;
    this.formName = formName;
  }
}

封装的工具类

/**
 * OkHttp工具类
 *
 * @author chenggaowei Created on 2018-05-09 23:45
 **/
public class OkHttpUtil {
  
  private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
  private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36";
  private static final OkHttpClient CLIENT;

  static {
    CLIENT = new OkHttpClient.Builder().addInterceptor(chain -> {
      Request request = chain.request().newBuilder()
          .addHeader("User-Agent", USER_AGENT)
          .addHeader("Connection", "keep-alive")
          .addHeader("Accept", "*/*")
          .build();
      return chain.proceed(request);
    })
        .connectTimeout(5, TimeUnit.SECONDS) //连接超时
        .writeTimeout(10, TimeUnit.SECONDS) //写超时
        .readTimeout(10, TimeUnit.SECONDS) //读超时
        .build();
  }

  /**
   * get请求,参数一般都在url里
   */
  public static String sendGet(String url) throws IOException {
    Request request = new Request.Builder().url(url).build();
    Response response = CLIENT.newCall(request).execute();
    return response.body().string();
  }

  /**
   * post提交json
   *
   * @param url 地址
   * @param jsonStr json字符串
   */
  public static String sendPost(String url, String jsonStr) throws IOException {
    RequestBody body = RequestBody.create(JSON_TYPE, jsonStr);
    Request request = new Request.Builder().url(url).post(body).build();
    Response response = CLIENT.newCall(request).execute();
    return response.body().string();
  }

  /**
   * post提交表单
   *
   * @param url 地址
   * @param params 参数
   * @param files 文件
   */
  public static String sendPost(String url, Map<String, Object> params, List<PostFile> files)
      throws IOException {
    if (CollectionUtils.isEmpty(files)) { // 没有文件上传的
      FormBody.Builder requestBody = new FormBody.Builder();
      if (MapUtils.isNotEmpty(params)) {
        params.forEach((k, v) -> requestBody.add(k, v.toString()));
      }
      FormBody body = requestBody.build();
      Request request = new Request.Builder().url(url).post(body).build();
      Response response = CLIENT.newCall(request).execute();
      return response.body().string();
    } else { // 有文件上传的
      MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
      if (MapUtils.isNotEmpty(params)) {
        params.forEach((k, v) -> requestBody.addFormDataPart(k, v.toString()));
      }
      if (CollectionUtils.isNotEmpty(files)) {
        for (PostFile postFile : files) {
          if (null != postFile.getFile()) {
            Path path = Paths.get(postFile.getFile().getName());
            String contentType = Files.probeContentType(path);
            if (StringUtils.isEmpty(contentType)) {
              contentType = "application/octet-stream";
            }
            RequestBody body = RequestBody.create(MediaType.parse(contentType), postFile.getFile());
            requestBody.addFormDataPart(postFile.getFormName(), postFile.getFile().getName(), body);
          }
        }
      }
      Request request = new Request.Builder().url(url).post(requestBody.build()).build();
      Response response = CLIENT.newCall(request).execute();
      return response.body().string();
    }
  }
  
}

如果需要在请求头携带参数类似自定义Header这种,这个时候需要把Builder封装一下

这个也可以封装成类似于PostFile这种数组

private static Builder getBuilder(String url, String header) {
    Builder builder = new Builder().url(url);
    if (StringUtils.isNotEmpty(token)) {
      builder.addHeader("header", header);
    }
    return builder;
  }

调用的地方以get和post为例

	/**
	 * get请求,参数一般都在url里
	 */
	public static String sendGet(String url, String header) throws IOException {
		Request request = getBuilder(url, header).build();
		Response response = CLIENT.newCall(request).execute();
		return response.body().string();
	}

	/**
	 * post提交json
	 *
	 * @param url 地址
	 * @param jsonStr json字符串
	 */
	public static String sendPost(String url, String header, String jsonStr) throws IOException {
		RequestBody body = RequestBody.create(JSON_TYPE, jsonStr);
		Request request = getBuilder(url, header).post(body).build();
		Response response = CLIENT.newCall(request).execute();
		return response.body().string();
	}

2018-20-29修改,添加文件下载方法(主要是下载图片)

package com.gwc.util;

import okhttp3.*;
import okhttp3.Request.Builder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * OkHttp工具类
 *
 * @author chenggaowei Created on 2018-05-08 13:04
 **/
public class OkHttpUtil {

    private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36";
    private static final OkHttpClient CLIENT;

    static {
        CLIENT = new OkHttpClient.Builder().addInterceptor(chain -> {
            Request request = chain.request().newBuilder()
                    .addHeader("User-Agent", USER_AGENT)
                    .addHeader("Connection", "keep-alive")
                    .addHeader("Accept", "*/*")
                    .build();
            return chain.proceed(request);
        }).connectTimeout(60, TimeUnit.SECONDS) //连接超时
                .writeTimeout(60, TimeUnit.SECONDS) //写超时
                .readTimeout(60, TimeUnit.SECONDS) //读超时
                .build();
    }

    /**
     * get请求,参数一般都在url里
     *
     * @param url 请求地址
     */
    public static String sendGet(String url) throws IOException {
        return sendGet(url, null);
    }

    /**
     * get请求
     *
     * @param url     请求地址
     * @param headers 请求头
     * @return
     * @throws IOException
     */
    public static String sendGet(String url, Map<String, Object> headers) throws IOException {
        Request request = getBuilder(url, headers).build();
        Response response = CLIENT.newCall(request).execute();
        return response.body().string();
    }

    /**
     * post 提交json
     *
     * @param url     请求地址
     * @param jsonStr json字符串
     * @return
     * @throws IOException
     */
    public static String sendPostJson(String url, String jsonStr) throws IOException {
        return sendPostJson(url, null, jsonStr);
    }

    /**
     * post 提交json
     *
     * @param url     请求地址
     * @param headers 请求头
     * @param jsonStr json字符串
     * @return
     * @throws IOException
     */
    public static String sendPostJson(String url, Map<?, ?> headers, String jsonStr) throws IOException {
        RequestBody body = RequestBody.create(JSON_TYPE, jsonStr);
        Request request = getBuilder(url, headers).post(body).build();
        Response response = CLIENT.newCall(request).execute();
        return response.body().string();
    }


    /**
     * post提交表单
     *
     * @param url    请求地址
     * @param params 参数
     * @return
     * @throws IOException
     */
    public static String sendPost(String url, Map<?, ?> params)
            throws IOException {
        return sendPost(url, null, params, null);
    }

    /**
     * post提交表单
     *
     * @param url    请求地址
     * @param params 参数
     * @param files  文件
     * @return
     * @throws IOException
     */
    public static String sendPost(String url, Map<?, ?> params, List<MultipartFile> files)
            throws IOException {
        return sendPost(url, null, params, files);
    }

    /**
     * post 提交表单
     *
     * @param url     请求地址
     * @param headers 请求头
     * @param params  参数
     * @param files   文件
     * @return
     * @throws IOException
     */
    public static String sendPost(String url, Map<?, ?> headers, Map<?, ?> params, List<MultipartFile> files)
            throws IOException {
        if (CollectionUtils.isEmpty(files)) { // 没有文件上传的
            FormBody.Builder requestBody = new FormBody.Builder();
            if (MapUtils.isNotEmpty(params)) {
                params.forEach((k, v) -> requestBody.add(k.toString(), v.toString()));
            }
            FormBody body = requestBody.build();
            Request request = new Request.Builder().url(url).post(body).build();
            Response response = CLIENT.newCall(request).execute();
            return response.body().string();
        } else { // 有文件上传的
            MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
            if (MapUtils.isNotEmpty(params)) {
                params.forEach((k, v) -> requestBody.addFormDataPart(k.toString(), v.toString()));
            }
            if (CollectionUtils.isNotEmpty(files)) {
                for (MultipartFile file : files) {
                    if (null != file) {
                        byte[] bytes = new byte[file.getInputStream().available()];
                        file.getInputStream().read(bytes);
                        RequestBody body = RequestBody.create(MediaType.parse(file.getContentType()), bytes);
                        requestBody.addFormDataPart(file.getName(), file.getOriginalFilename(), body);
                    }
                }
            }
            Request request = getBuilder(url, headers).post(requestBody.build()).build();
            Response response = CLIENT.newCall(request).execute();
            return response.body().string();
        }
    }

    /**
     * 根据url下载图片到本地,这里不校验图片路径的正确与否
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static File downloadImage(String url) throws Exception {
        String ext = FilenameUtils.getExtension(url);
        if (StringUtils.isEmpty(ext)) {
            ext = "png";
        }
        String regex = "\\.[a-zA-Z]+$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher("." + ext);
        if (!matcher.find()) {
            ext = "png";
        }
        String pathname = FileUtil.getTempPath() + File.separator + System.currentTimeMillis() + "." + ext;
        File file = new File(pathname);
        Request request = new Request.Builder().url(url).build();
        Call call = CLIENT.newCall(request);
        Response response = call.execute();
        byte[] buf = new byte[2048];
        int len;
        InputStream inputStream = response.body().byteStream();
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        while ((len = inputStream.read(buf)) != -1) {
            fileOutputStream.write(buf, 0, len);
        }
        fileOutputStream.flush();
        return file;
    }

    private static Builder getBuilder(String url, Map<?, ?> headers) {
        Request.Builder builder = new Request.Builder().url(url);
        if (MapUtils.isNotEmpty(headers)) {
            headers.forEach((k, v) -> builder.addHeader(k.toString(), v.toString()));
        }
        return builder;
    }

    public static void main(String[] args) throws Exception {
        String url = "http://cj.jj20.com/d/cj0.php?p=/up/allimg/1111/10141Q22930/1Q014122930-1.jpg&w=1536&h=864";
        // String url = "123";
        System.out.println(downloadImage(url).getAbsolutePath());
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值