码迷,mamicode.com
首页 > Web开发 > 详细

HttpUtils——OkHttp版本

时间:2019-10-17 01:25:31      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:函数   int   code   desktop   http   host   dia   pen   nbsp   

已经不开发安卓了,目前HttpClient用的多,此版本留做纪念

cn.seaboot.common是我的工具包,等过段时间开源,功能同函数名一样,属于常规代码,有开发经验应该可以轻易读懂

package cn.seaboot.common.net;

import cn.seaboot.common.core.CommonUtils;
import cn.seaboot.common.core.Converter;
import cn.seaboot.common.exception.ServiceException;
import cn.seaboot.common.file.IOUtils;
import cn.seaboot.common.file.MimeUtils;
import okhttp3.*;
import okio.BufferedSink;
import org.apache.http.HttpStatus;

import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;


/**
 * 基于OkHttp
 */
public class OkHttpUtils {
    private static OkHttpClient okHttpClient;

    private OkHttpUtils() {
        okHttpClient = new OkHttpClient();
    }

    /**
     * 异常校验
     */
    private static ResponseBody validResponse(Response res) {
        if (res.code() != HttpStatus.SC_OK) {
            throw new ServiceException("okhttp visit url exception :" + res.code());
        }
        return res.body();
    }

    /**
     * 构建表单
     */
    public static FormBody getFormBody(String url, HashMap<String, ?> map) {
        FormBody.Builder builder = new FormBody.Builder();
        String v;
        for (Map.Entry<String, ?> p : map.entrySet()) {
            v = Converter.toString(p.getValue());
            builder.add(p.getKey(), v);
        }
        return builder.build();
    }

    /**
     * post请求
     */
    public static Request getPostMethod(String url, HashMap<String, ?> map) {
        return new Request.Builder()
            .url(url)
            .post(getFormBody(url, map))
            .build();
    }

    public static String getUrl(String url, HashMap<String, ?> map){
        StringBuilder sb = new StringBuilder(url);
        if (url.indexOf(‘?‘) < 0) {
            sb.append(‘?‘);
        }
        String v;
        for (Map.Entry<String, ?> p : map.entrySet()) {
            v = Converter.toString(p.getValue());
            sb.append(p.getKey()).append(‘=‘).append(v).append(‘&‘);
        }
        sb.setLength(sb.length() - 1);
        return sb.toString();
    }

    /**
     * get请求
     */
    public static Request getGetMethod(String url, HashMap<String, ?> map) throws IOException {
        return new Request.Builder()
            .url(getUrl(url, map))
            .get()
            .build();
    }

    public static String execute(Request request) throws IOException {
        Call call = okHttpClient.newCall(request);
        return validResponse(call.execute()).string();
    }

    public static void download(Request request, OutputStream os) throws IOException {
        Call call = okHttpClient.newCall(request);
        IOUtils.copy(validResponse(call.execute()).byteStream(), os);
    }


    public static String postFormData(String url, HashMap<String, ?> map, String name, File file) throws IOException {
        String v = file.getName();
        String suffix = v.substring(v.lastIndexOf(‘.‘) + 1);
        String mime = MimeUtils.getMimeFromSuffix(suffix);
        //mime类型
        RequestBody fileBody = RequestBody.create(MediaType.parse(mime), file);
        MultipartBody.Builder builder = new MultipartBody.Builder()
            .addFormDataPart(name, v, fileBody);

        if(!CommonUtils.isEmpty(map)){
            for (Map.Entry<String, ?> p : map.entrySet()) {
                v = Converter.toString(p.getValue());
                builder.addFormDataPart(p.getKey(), v);
            }
        }
        System.out.println(mime);
        Request request = new Request.Builder()
            .url(url)
            .post(builder.build())
            .build();
        return execute(request);
    }

    public static String postFormData(String url, Map<String, ?> map, String name, String mime, InputStream is) throws IOException {
        RequestBody fileBody = new RequestBody() {
            @Override
            @Nullable
            public MediaType contentType() {
                return MediaType.parse(mime);
            }

            @Override
            public long contentLength() {
                try {
                    return is.available();
                } catch (IOException e) {
                    //IGNORE
                }
                return -1;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                IOUtils.copy(is,sink.outputStream());
            }
        };

        MultipartBody.Builder builder = new MultipartBody.Builder()
            .addFormDataPart(name, name, fileBody);
        String v;
        if(!CommonUtils.isEmpty(map)){
            for (Map.Entry<String, ?> p : map.entrySet()) {
                v = Converter.toString(p.getValue());
                builder.addFormDataPart(p.getKey(), v);
            }
        }
        Request request = new Request.Builder()
            .url(url)
            .post(builder.build())
            .build();
        return execute(request);
    }

    public static void main(String[] args) throws IOException {
        new OkHttpUtils();
        String url = "http://localhost:8080/xbry/md2001/ammunCode/test";
        String path = "C:\\Users\\Administrator\\Desktop\\logo_144.png";
        Map<String, Object> map = new HashMap<>();
        map.put("3", "4");
        File file = new File(path);
        postFormData(url, map, "file", "image/png", IOUtils.openFileInputStream(file));
    }
}

 

HttpUtils——OkHttp版本

标签:函数   int   code   desktop   http   host   dia   pen   nbsp   

原文地址:https://www.cnblogs.com/chenss15060100790/p/11689403.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!