okhttp的get/post请求和上传图像

public class OkHttpUtils {
    private static final String TAG = "OKHttpUtils----";
    private static OkHttpUtils okHttpUtils=null;
    private MyHandler myHandler=new MyHandler();
    private LoginListener onLoginListener;
    public static OkHttpUtils getInstance(){
        if (okHttpUtils==null){
            okHttpUtils=new OkHttpUtils();
        }
        return okHttpUtils;
    }
    //get请求
    public void okGet(String url,String mobile,String password){
        String urll=url+"?mobile="+mobile+"&password="+password;
        //创建okhttpClient
        OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new MyIntercepter()).build();
        //用request请求,将URL和参数进行封装
        Request request = new Request.Builder().url(urll).build();
        //call是请求队列,
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = myHandler.obtainMessage();
                message.what=0;
                message.obj = e.getMessage();
                myHandler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message message = myHandler.obtainMessage();
                message.what=1;
                message.obj=response.body().string();
                myHandler.sendMessage(message);
            }
        });
    }
    //post请求
    public void okPost(String url, Map params){
        //创建OKHttpClient
        OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new MyIntercepter()).build();
        FormBody.Builder builder = new FormBody.Builder();
        Set keys = params.keySet();
        for (String key : keys){
            String value = params.get(key);
            builder.add(key,value);
        }
        FormBody body = builder.build();
        Request request = new Request.Builder().url(url).post(body).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = myHandler.obtainMessage();
                message.what=0;
                message.obj=e.getMessage();
                myHandler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message message = myHandler.obtainMessage();
                message.what=1;
                message.obj=response.body().string();
                myHandler.sendMessage(message);
            }
        });
    }

    class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int w = msg.what;
            switch (w){
                case 0:
                    String error = (String) msg.obj;
                    onLoginListener.loginError(error);
                    break;
                case 1:
                    String json = (String) msg.obj;
                    onLoginListener.loginSuccess(json);
                    break;
            }
        }
    }
    public interface LoginListener{
        void loginSuccess(String json);
        void loginError(String error);
    }
    //提供一个外部的访问方法
    public void setOnLoginListener(LoginListener onLoginListener){
        this.onLoginListener=onLoginListener;
    }
    //拦截器实现公共参数的拼接
    class MyIntercepter implements Interceptor{

        @Override
        public Response intercept(Chain chain) throws IOException {
            //获取请求
            Request request = chain.request();
            RequestBody body = request.body();
            if (body instanceof FormBody){
                FormBody.Builder builder = new FormBody.Builder();
                for (int i=0;i<((FormBody) body).size();i++){
                    String key = ((FormBody) body).name(i);
                    String value = ((FormBody) body).value(i);
                    //添加
                    builder.add(key,value);
                }
                builder.add("source","android");
                builder.add("token","appVersion");
                FormBody newBody = builder.build();
                //创建新的请求
                Request request1 = request.newBuilder().post(newBody).build();
                Response response = chain.proceed(request1);
                return response;
            }
            return null;
        }
    }
    //上传头像
    public void upLoadImage(String upload_url, File file){
        //创建okhClient
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建MultiparBody
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
   //设置参数
        MediaType mediaType = MediaType.parse("image/png");
        builder.addFormDataPart("file",file.getName(),RequestBody.create(mediaType,file));
        //添加其他参数
        builder.addFormDataPart("uid","71");
        MultipartBody body = builder.build();
        Request request = new Request.Builder().url(upload_url).post(body).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure() returned: " + "shibai---" + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "onResponse() returned: " + response.body().string());
            }
        });
    }
}

你可能感兴趣的:(okhttp的get/post请求和上传图像)