OkHttp应用和封装

晚自习练习,OkHttp的封装调用

工具类

package com.example.app_three;

import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;

public class OkHttpUtils {
    private OkHttpClient client;
    private static OkHttpUtils httpUtils=null;

    public static OkHttpUtils getInstance(){
        if( httpUtils==null){
            synchronized (Object.class){
                if( httpUtils==null){
                    httpUtils=new OkHttpUtils();
                }
            }
        }
        return httpUtils;
    }

    private OkHttpUtils(){
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(
                new HttpLoggingInterceptor.Logger() {
                    @Override
                    public void log(String message) {
                        Log.d("123321", "石卓凡: " + message);
                    }
                }
        );
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        Interceptor interceptor = new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                Request.Builder header = chain.request().newBuilder().header("token", "szf");
                Request request = header.build();
                return chain.proceed(request);
            }
        };

        client=new OkHttpClient.Builder()
                .readTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(10,TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .addInterceptor(httpLoggingInterceptor)
                .build();
    }

    public void doGet(String url, final MyOnClick listener){
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(url)
                .get()
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.no(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                listener.ok(response.body().string());
            }
        });

    }

    public void doPost(String url, HashMap<String,String> map, final MyOnClick click){

        FormBody.Builder builder = new FormBody.Builder();
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            builder.add(entry.getKey(),entry.getValue());
        }
        FormBody formBody = builder.build();

        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        client.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        click.no(e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        click.ok(response.body().string());
                    }
                });
    }

    public void doDownLoad(String url, final String path, final MyOnClick click){
        final Request.Builder builder = new Request.Builder();
        Request request = builder.url(url)
                .get()
                .build();
        client.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        click.no(e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        ResponseBody body = response.body();
                        InputStream is = body.byteStream();
                        byte[] bytes = new byte[1024];
                        int len=0;
                        while( (len=is.read(bytes))!=-1){
                            FileOutputStream fos = new FileOutputStream(path);
                            fos.write(bytes,0,len);
                        }
                    }
                });
    }

    public void doUpLoad(String url,String path,String fileName,String type,final MyOnClick click){
        MultipartBody.Builder body = new MultipartBody.Builder();
        body.setType(MultipartBody.FORM)
                .addFormDataPart("file"
                        , fileName
                        , RequestBody.create(MediaType.parse(type),new File(path)))
                .build();
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        client.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        click.no(e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        click.ok(response.body().string());
                    }
                });
    }
}

返回消息的接口

package com.example.app_three;

public interface MyOnClick {
    void ok(String json);
    void no(String message);
}

主界面

package com.example.app_three;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.example.app_three.Model.OkHttpModelIpml;

import java.util.HashMap;

public class MainActivity extends AppCompatActivity {
    private OkHttpUtils okHttpUtils=OkHttpUtils.getInstance();
    private static final String TAG = "123321";
    private OkHttpModelIpml model;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        model=new OkHttpModelIpml();
    }

    public void click(View view) {
        switch (view.getId()) {
            case R.id.button_get:
                get();
                break;
            case R.id.button_post:
                post();
                break;
            case R.id.button_downLoad:
                downLoad();
                break;
        }
    }

    private void downLoad() {

    }

    private void post() {
        //siteid=78703&act=column&ctype=2&mid=16
        HashMap<String, String> hm = new HashMap<>();
        hm.put("siteid","78703");
        hm.put("act","column");
        hm.put("ctype","2");
        hm.put("mid","16");
        model.MyPost("http://api.yunzhancn.cn/api/app.interface.php?", hm, new MyOnClick() {
            @Override
            public void ok(String json) {
                Log.i(TAG, "ok: "+json);
            }

            @Override
            public void no(String message) {
                Log.i(TAG, "no: "+message);
            }
        });
//        okHttpUtils.doPost("http://api.yunzhancn.cn/api/app.interface.php?"
//                , hm, new MyOnClick() {
//                    @Override
//                    public void ok(String json) {
//                        Log.i(TAG, "ok: "+json);
//                    }
//
//                    @Override
//                    public void no(String message) {
//                        Log.i(TAG, "no: "+message);
//                    }
//                });
    }

    private void get() {
        okHttpUtils.doGet("http://api.yunzhancn.cn/api/app.interface.php?siteid=78703&act=column&ctype=2&mid=16", new MyOnClick() {
            @Override
            public void ok(String json) {
                Log.i(TAG, "ok: "+json);
            }

            @Override
            public void no(String message) {
                Log.i(TAG, "no: "+message);
            }
        });
    }


}

对应的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="get"
        android:id="@+id/button_get"
        android:onClick="click"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="post"
        android:id="@+id/button_post"
        android:onClick="click"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下载"
        android:id="@+id/button_downLoad"
        android:onClick="click"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="上传"
        android:id="@+id/button_upLoad"
        android:onClick="click"
        />


</LinearLayout>

model接口

调用工具类的方法

package com.example.app_three.Model;

import com.example.app_three.MyOnClick;

import java.util.HashMap;

public interface OkHttpModel {
    void MyGet(String url, MyOnClick click);
    void MyPost(String url, HashMap<String,String> hm, MyOnClick click);
    void MyDownLoad(String url,String path, MyOnClick click);
    void MyGet(String url,String path,String fileName,String type, MyOnClick click);
}

实现Model接口

package com.example.app_three.Model;

import com.example.app_three.MyOnClick;
import com.example.app_three.OkHttpUtils;

import java.util.HashMap;

public class OkHttpModelIpml  implements OkHttpModel{
    private OkHttpUtils utils;

    public OkHttpModelIpml() {
        utils=OkHttpUtils.getInstance();
    }

    @Override
    public void MyGet(String url, MyOnClick click) {
        utils.doGet(url,click);
    }

    @Override
    public void MyPost(String url, HashMap<String, String> hm, MyOnClick click) {
        utils.doPost(url,hm,click);
    }

    @Override
    public void MyDownLoad(String url, String path, MyOnClick click) {
        utils.doDownLoad(url,path,click);
    }

    @Override
    public void MyGet(String url, String path, String fileName, String type, MyOnClick click) {
        utils.doUpLoad(url,path,fileName,type,click);
    }
}
上一篇:OKHttp拦截器之责任链模式


下一篇:java – 当互联网断开连接时重新连接OkHttp websocket