Android_OkHttp封装

首先:布局控件

<?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="com.bwei.www.okhttpfengzhuang.MainActivity"
    android:orientation="vertical"
    >
<TextView
    android:id="@+id/tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="测试"/>
    <Button
        android:id="@+id/btn_get"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="get请求"/>
    <Button
        android:id="@+id/btn_post"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="post请求"/>
</LinearLayout>


一:定义一个接口里面有请求成功和失败的方法

    public interface CallBack {  
        void onSuccess(Object o);  
        void onFailed(Exception e);  
    }  

二:工具类中

    package activity.example.com.httputils;  
      
    import android.os.Handler;  
      
    import com.google.gson.Gson;  
      
    import java.io.IOException;  
    import java.util.Map;  
      
    import okhttp3.Call;  
    import okhttp3.Callback;  
    import okhttp3.FormBody;  
    import okhttp3.OkHttpClient;  
    import okhttp3.Request;  
    import okhttp3.Response;  
      
   
    public class HttpUtils {  
        private static volatile HttpUtils instance;  
      
        private static Handler handler = new Handler();  
      
        private HttpUtils(){  
      
        }  
        public static HttpUtils getInstance() {  
            if (instance == null) {  
                synchronized (HttpUtils.class) {  
                    if (instance == null) {  
                        instance = new HttpUtils();  
                    }  
                }  
            }  
            return instance;  
        }  
        //get请求  
        public void get(String url, Map<String,String> map, final CallBack callBack, final Class c){  
            //对url和参数做拼接处理  
            StringBuffer stringBuffer = new StringBuffer();  
            stringBuffer.append(url);  
            //判断是否存在?   if中是存在  
            if(stringBuffer.indexOf("?")!=-1 ){  
                //判断?是否在最后一位    if中是不在最后一位  
                if(stringBuffer.indexOf("?")!=stringBuffer.length()-1){  
                    stringBuffer.append("&");  
                }  
            }else{  
                stringBuffer.append("?");  
            }  
            for(Map.Entry<String,String> entry:map.entrySet()){  
                stringBuffer.append(entry.getKey())  
                            .append("=")  
                            .append(entry.getValue())  
                            .append("&");  
            }  
        //判断是否存在&   if中是存在  
        if(stringBuffer.indexOf("&")!=-1){  
            stringBuffer.deleteCharAt(stringBuffer.lastIndexOf("&"));  
        }  
      
      
            //1:创建OkHttpClient对象  
            OkHttpClient okHttpClient = new OkHttpClient();  
            //2:创建Request对象  
            final Request request = new Request.Builder()  
                    .get()  
                    .url(stringBuffer.toString())  
                    .build();  
            //3:创建Call对象  
            Call call = okHttpClient.newCall(request);  
            //4:请求网络  
            call.enqueue(new Callback() {  
                //请求失败  
                @Override  
                public void onFailure(Call call, final IOException e) {  
                    handler.post(new Runnable() {  
                        @Override  
                        public void run() {  
                            callBack.onFailed(e);  
                        }  
                    });  
                }  
                //请求成功  
                @Override  
                public void onResponse(Call call, Response response) throws IOException {  
                    String result = response.body().string();  
                    //拿到数据解析  
                    final Object o = new Gson().fromJson(result, c);  
                    //当前是在子线程,回到主线程中  
                    handler.post(new Runnable() {  
                        @Override  
                        public void run() {  
                            //回调  
                            callBack.onSuccess(o);  
                        }  
                    });  
                }  
            });  
      
        }  
        //post请求  
        public void post(String url, Map<String,String> map, final CallBack callBack, final Class c){  
            //1:创建OkHttpClient对象  
            OkHttpClient okHttpClient = new OkHttpClient();  
            //2:提供post请求需要的body对象  
            FormBody.Builder builder = new FormBody.Builder();  
            for(Map.Entry<String,String> entry:map.entrySet()){  
                builder.add(entry.getKey(),entry.getValue());  
            }  
            FormBody body = builder.build();  
            //3:创建Request对象  
            final Request request = new Request.Builder()  
                    .post(body)  
                    .url(url)  
                    .build();  
            //4:创建Call对象  
            Call call = okHttpClient.newCall(request);  
            //5:请求网络  
            call.enqueue(new Callback() {  
                //请求失败  
                @Override  
                public void onFailure(Call call, final IOException e) {  
                    handler.post(new Runnable() {  
                        @Override  
                        public void run() {  
                            callBack.onFailed(e);  
                        }  
                    });  
                }  
                //请求成功  
                @Override  
                public void onResponse(Call call, Response response) throws IOException {  
                    String result = response.body().string();  
                    //拿到数据解析  
                    final Object o = new Gson().fromJson(result, c);  
                    //当前是在子线程,回到主线程中  
                    handler.post(new Runnable() {  
                        @Override  
                        public void run() {  
                            //回调  
                            callBack.onSuccess(o);  
                        }  
                    });  
                }  
            });  
        }  
      
    }  


三:MainActivity引用


    package activity.example.com.httputils;  
      
    import android.support.v7.app.AppCompatActivity;  
    import android.os.Bundle;  
    import android.view.View;  
    import android.widget.Button;  
    import android.widget.TextView;  
      
    import java.util.HashMap;  
    import java.util.Map;  
      
    public class MainActivity extends AppCompatActivity {  
      
        private Button get;  
        private TextView text;  
      
        @Override  
        protected void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.activity_main);  
            get = (Button)findViewById(R.id.get);  
            text = (TextView)findViewById(R.id.text);  
            get.setOnClickListener(new View.OnClickListener() {  
                @Override  
                public void onClick(View view) {  
                    Map<String,String> map = new HashMap<String, String>();  
                    map.put("mobile","00000000000");  
                    map.put("password","123456");  
                    HttpUtils.getInstance().get("http://120.27.23.105/user/login", map,  
                            new CallBack() {  
                                @Override  
                                public void onSuccess(Object o) {  
                                    //o请求回来的数据,已经解析完  
                                    final User user = (User)o;  
                                    //请求出来的数据展示到textview上  
                                    text.setText(user.getMsg());  
                                }  
      
                                @Override  
                                public void onFailed(Exception e) {  
      
                                }  
                            },User.class);//最后一个参数是解析的实体类  
                }  
            });  
        }  
    }  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值