Okhttp的基本使用方法 及其封装

Okhttp的简单使用 及其封装

导包:
compile 'com.squareup.okhttp3:okhttp:3.8.1'


public class NetUtils {
    //单例模式,因为内部封装了很多信息例如session,所以最好使用单例模式
    static final OkHttpClient client = new OkHttpClient();

    public static void get(String url, HashMap<String, String> map, final OnNet getter) {
        final String urls = getUrl(url, map);
        new Thread(new Runnable() {
            @Override
            public void run() {
                //请求
                Request request = new Request.Builder().url(urls).build();
                //响应
                Response response = null;
                try {
                    response = client.newCall(request).execute();
                    //调用response.isSuccessful()判断是否成功
                    if (response.isSuccessful()){
                        //response.body()有很多方法,可以把数据流转换成各种格式
                        getter.onSuccessed(response.body().string());
                    }else{
                        getter.onFailed(response.body().string());
                    }
                } catch (IOException e) {
                    getter.onFailed(e.getCause()+"");
                }
            }
        }).start();
    }
    //将map参数拼接成get所使用的url
    public static String getUrl(String url,HashMap map){
        if (map==null||map.size()==0){
            return url;
        }
        StringBuilder sb=new StringBuilder();
        sb.append(url);
        sb.append("?");

        Iterator iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            sb.append(key);
            sb.append("=");
            sb.append(value);
            sb.append("&");
        }
        url = sb.substring(0, sb.length() - 1);
        return url;
    }

    public static void post(final String url, final HashMap<String, String> map, final OnNet poster){
        if (map==null||map.size()==0){
            get(url,null,poster);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                //使用new FormBody.Builder()来传入请求参数
                FormBody.Builder builder = new FormBody.Builder();
                for(String key:map.keySet()){
                    String value = map.get(key);
                    builder.add(key,value);
                }
                FormBody body = builder.build();
                //将body传入请求中
                Request request = new Request.Builder().url(url).post(body).build();
                Response response = null;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()){
                        poster.onSuccessed(response.body().string());
                    }else{
                        poster.onFailed(response.body().string());
                    }
                } catch (IOException e) {
                    poster.onFailed(e.getCause()+"");
                }
            }
        }).start();
    }
}

原生网络请求的基本使用及其封装

public class NetUtils {
    public static String doPost(String urlStr, HashMap<String, String> map) {
        if (map==null){
            map=new HashMap<String,String>();
        }
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            String cache = parseParams(map);
            conn.setDoOutput(true);
            conn.getOutputStream().write(cache.getBytes());
            if (conn.getResponseCode()==200){
                InputStream is = conn.getInputStream();
                BufferedReader bs = new BufferedReader(new InputStreamReader(is));
                return bs.readLine();
            }
        } catch (MalformedURLException e) {
            Log.v("meee", "url格式异常");
        } catch (IOException e) {
            Log.v("meee", "请求中Io异常");
        }
        return "";
    }

    public static String doGet(String urlStr, HashMap<String, String> map) {
        if (map==null){
            map=new HashMap<String,String>();
        }
        String cache = parseParams(map);
        try {

            URL url = new URL(urlStr+"?"+cache);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            if (conn.getResponseCode()==200){
                InputStream is = conn.getInputStream();
                BufferedReader bs = new BufferedReader(new InputStreamReader(is));
                return bs.readLine();
            }
        } catch (MalformedURLException e) {
            Log.v("meee", "url格式异常");
        } catch (IOException e) {
            Log.v("meee", "请求中Io异常");
        }
        return "";
    }

    @NonNull
    private static String parseParams(HashMap<String, String> map) {
        String cache = "";
        if (map.isEmpty()||map==null){
            return "";
        }
        for (Map.Entry<String, String> kv : map.entrySet()) {
            cache += kv.getKey() + "=" + kv.getValue() + "&";
        }
        cache = cache.substring(0, cache.length() - 1);
        return cache;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值