zoukankan      html  css  js  c++  java
  • 安卓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下的,引入时需注意。

  • 相关阅读:
    异构网络中的并行传输问题
    如何编程实现快速获取一个整型数中的bit流中1的个数
    对单例模式的一个简单思考
    OsgEearh 中的 FeatureEditor的实现原理
    关于在osgearth 中 出现 arial.ttf : file not handled 的问题
    Qt 中 this->size() this->rect() event->size() 三者差异
    Qt 中QPainter 使用中出现的问题
    对c语言中static函数的理解
    对声明和定义的理解
    个人对头文件的理解
  • 原文地址:https://www.cnblogs.com/wuyoucao/p/6817410.html
Copyright © 2011-2022 走看看