fork me on github

安卓OKhttp请求封装

  目前安卓开发中使用的网络工具为OKhttp,但是okhttp的使用还不是很方便,在okhttp的基础上再对请求进行封装会极大的方便网络调用。

  下面直接上代码。

请求封装

public class HttpUtil {
    public static void sendOKHttpRequest(String address, Map<String,String> head,Map<String,String> body,okhttp3.Callback callback){
        OkHttpClient client=new OkHttpClient();
        Request.Builder builder=new Request.Builder().url(address);
        if(head!=null&&head.size()>0){
            for (Map.Entry<String, String> entry : head.entrySet()) {
                builder.addHeader(entry.getKey(),entry.getValue());
            }
        }
        FormBody.Builder formBody = new FormBody.Builder();
        if(body!=null&&body.size()>0){
            for (Map.Entry<String, String> entry : head.entrySet()) {
                formBody.add(entry.getKey(),entry.getValue());
            }
        }
        RequestBody requestBody = formBody.build();
        Request request=builder.post(requestBody).build();
        client.newCall(request).enqueue(callback);
    }
}

上面对okhttp的put请求进行了简单封装,四个参数分别是

  1.请求地址

  2.请求头,以map的形式传入,如不需要可传入null

  3.携带参数,同样以map的形式传入,如无参数传入null

  4.回调函数

代码中调用

  

     Map<String,String> body=new HashMap<String, String>();
     body.put("userName",loginName);
     body.put("password",password);

    HttpUtil.sendOKHttpRequest(getString(R.string.ip)+"/xxx/Login",null,body,new Callback(){ @Override public void onFailure(Call call, IOException e) { //请求失败 } @Override public void onResponse(Call call, Response response) throws IOException { final String responseText=response.body().string(); //请求成功 } });

注意Callback为OKhttp下的,引入时需注意。

posted @ 2017-05-06 17:20  烦嚣的人  阅读(2370)  评论(0编辑  收藏  举报