android开发 之OkHttp二次封装(android 访问网络)

 这个是本人在使用的一个网络请求,根据自己的需求进行修改的,对于自己完全够用。大家有需要可以根据自己的项目修改成自己需要的。如果有什么问题,还希望告知。

使用时继承该类即可


import android.os.Handler;
import android.os.Message;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by xiaobao on 2018/9/24.
 */

public abstract class HttpBase {
    private String url="192.168.1.1";//服务器地址
    private Handler handler;
    private int SuccessCode;//成功时message.what

 

    //post方法需要重写此方法
    public FormBody setFormBody(FormBody formBody){
        formBody = new FormBody.Builder()
                //.add("type","addshop")
                .build();
        return formBody;
    }

//post访问网络
    public void  httpPost (String urls, final Handler handler, final int SuccessCode) {
        //开启网络请求
        this.handler=handler;
        this.SuccessCode=SuccessCode;
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
        FormBody formBody = null;
        formBody=setFormBody(formBody);
        String tempurl=urls.startsWith("http")?urls:url+urls;
        final Request request = new Request.Builder()
                .url(tempurl)//请求的url
                .post(formBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
    //将空字符串给子类处理,实例化某些数据,防止出现空指针异常,本人项目需要,大家可自行修改
                sendMessage("");
            }

            @Override
            // 获取到服务器数据。注意:即使是 404 等错误状态也是获取到服务器数据
            public void onResponse(Call call, Response response) throws IOException {

                if (response.isSuccessful()){
                    String rerStr=response.body().string();
                    sendMessage(rerStr);
                }
            }
        });

    }
    //get访问网络
    public  void HttpGet(String urls, final Handler handler, final int SuccessCode) {
        this.handler=handler;
        this.SuccessCode=SuccessCode;
        OkHttpClient okHttpClient = new OkHttpClient();
        String tempurl=urls.startsWith("http")?urls:url+urls;
        Request request = new Request.Builder().url(tempurl).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
               // Msg msg=new Msg(5000,"服务器通信异常,请检查网络是否可用");
               // messages(msg);
               // String rerStr=response.body().string();
                sendMessage("");
            }

            @Override
            // 获取到服务器数据。注意:即使是 404 等错误状态也是获取到服务器数据
            public void onResponse(Call call, Response response) throws IOException {

                if (response.isSuccessful()){
                    String rerStr=response.body().string();
                    sendMessage(rerStr);
                }
            }
        });
    }
//实现该方法对返回数据进行处理
    public abstract void sendMessage(String reStr) ;
//将处理好的信息返回
    public void messages( Object object){
        Message message=new Message();
        message.what=SuccessCode;
        message.obj=object;
        handler.sendMessage(message);
    }
}

get方法调用演示

UserEntity 是用户实体,这里就不给出了

url链接如果不是http开头,那么会使用httpBase里面的url地址


public class LoginHttp extends HttpBase {
//使用时调用此方法
    public void login(Handler handler, String username, String password) {
        String url = "/api/user/login?username="+username+"&password="+password;
        super.HttpGet(url, handler, 0x200);
    }
//处理返回数据
    @Override
    public void sendMessage(String reStr) {
        UserEntity userEntity = new UserEntity();
        try {
            JSONObject jsonObject = new JSONObject(reStr);
            int code = jsonObject.getInt("code");
            userEntity.setCode(code);
            userEntity.setMsg(jsonObject.getString("msg"));
            if (code == 1000) {
                userEntity.setUsername(jsonObject.getString("username"));
                userEntity.setPhone(jsonObject.getString("phone"));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        super.messages(userEntity);
    }
}

post方法调用演示
 



import android.os.Handler;
import android.os.Message;

import org.json.JSONException;
import org.json.JSONObject;

import cn.mvapi.daogouba.entity.Msg;
import cn.mvapi.daogouba.ui.BaseActivity;
import okhttp3.FormBody;

/**
 * Created by 小宝 on 2018/10/23.
 */

public class HeadImgHttp extends HttpBase{
    private String imgbase;
    private String imgname;
//使用时调用次方法
    public void upImg(Handler handler, String imgbase,String imgname) {
        this.imgbase = imgbase;
        this.imgname=imgname;
        super.httpPost("/api/user/upload", handler, 0x200);
    }
//处理返回数据
    @Override
    public void sendMessage(String reStr) {
        Msg msg=new Msg();
      
        try {
            JSONObject jsonObject=new JSONObject(reStr);
            msg.setCode(jsonObject.getInt("code"));
            msg.setMsg(jsonObject.getString("msg"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        super.messages(msg);
    }
    //参数传递
    @Override
    public FormBody setFormBody(FormBody formBody) {
        formBody = new FormBody.Builder()
                .add("imgStr", imgbase)
                .add("imgname",imgname)
                .build();
        return formBody;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41780372/article/details/84654185