OkhttpUtils

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sui_yz/article/details/79965479
package com.example.okhttpdemo.net;

import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkhttpUtils {
    //private static OkhttpUtils okhttpUtils = new OkhttpUtils();//饿汉式
    private static OkhttpUtils okhttpUtils;
    private final OkHttpClient okHttpClient;

    //构造方法要私有化
    private OkhttpUtils() {
        //创建OkhttpClient
        okHttpClient = new OkHttpClient();
    }

    //懒汉式
    public static OkhttpUtils getInstance() {
        if (okhttpUtils == null) {
            okhttpUtils = new OkhttpUtils();
        }
        return okhttpUtils;
    }

    /*饿汉式
    public static OkhttpUtils getInstance(){
        return okhttpUtils;
    }*/


    /**
     * GET请求
     *
     * @param url
     * @param params
     */
    public void doGet(String url, Map<String, String> params, final OnNetListener onNetListener) {
        //判断params是否为null
        if (params != null) {
            StringBuilder sb = new StringBuilder();
            sb.append("?");
            //拼接参数
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(entry.getKey());
                sb.append("=");
                sb.append(entry.getValue());
                sb.append("&");
            }
            //?mobile=12354678954&password=123456&
            String s = sb.toString();
            String strParam = s.substring(0, s.length() - 1);
            url += strParam;
            Log.e("sdfasdf", "url = " + url);
        }
        //创建Request对象
        Request request = new Request.Builder().url(url).build();
        //发送请求
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                onNetListener.onFailed(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String string = response.body().string();
                Log.e("MainActivity", "string = " + string);
                onNetListener.onSuccess(string);
            }

        });
    }

    /**
     * GET请求
     */
    public void doGet(String url) {
        //创建Requet对象
        Request request = new Request.Builder().url(url).build();
        //进行请求
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("MainActivity", "onFailure");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String string = response.body().string();
                Log.e("MainActivity", "string = " + string);
            }
        });

    }


    public void doPost(String url, Map<String, String> params) {
        if (params != null) {
            //创建FormBody用于封装参数
            FormBody.Builder fBuilder = new FormBody.Builder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                fBuilder.add(entry.getKey(), entry.getValue());
            }
            FormBody formBody = fBuilder.build();
            Request.Builder builder = new Request.Builder();
            builder.url(url);
            builder.post(formBody);
            //创建Request
            Request request = builder.build();

            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String string = response.body().string();
                    Log.e("MainActivity", "string = " + string);
                }
            });
        }
    }

    /**
     * 上传
     *
     * @param url
     * @param fileName
     * @param file
     */
    public void update(String url, Map<String, String> params, String fileName, File file) {

        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.addFormDataPart(entry.getKey(), entry.getValue());
            }

        }
        builder.addFormDataPart("file", fileName, RequestBody.create(MediaType.parse("application/octet-stream"),
                file));
        MultipartBody multipartBody = builder.build();
        Request requeset = new Request.Builder().url(url).post(multipartBody).build();
        okHttpClient.newCall(requeset).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });
    }
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页