OKHttp

首先导入 依赖
在这里插入图片描述


# package soexample.umeng.com.okhttp_demo_day12; 

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import soexample.umeng.com.okhttp_demo_day12.utils.OkHttpUtils;

/**
 * OKHttp3 ?
 * 网络处理框架 处理网络接口
 * 1:导入依赖
 * OKHttp3处理网络有两种方式
 * 1:同步  execute  get和post 必须要放在子线程中
 * 2:异步  enqueue
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button Send_Btn;
    private TextView Tv_Get;
    private String mUrl = "http://www.zhaoapi.cn/home/getHome";
    private String mPostUrl = "http://www.zhaoapi.cn/user/login";
															   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        Send_Btn = (Button) findViewById(R.id.Send_Btn);
        Tv_Get = (TextView) findViewById(R.id.Tv_Get);

        Send_Btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.Send_Btn:
//                sendNet();
//                sendPost();
//                asyncSend();
//                asyncPost();
                utilsGet();
                break;
        }
    }

    //同步处理get方式 必须放在子线程里
    private void sendNet() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    //1:学什么都能new出一个对象来
                    OkHttpClient okHttpClient = new OkHttpClient();
                    //Request就是请求的类
                    Request request = new Request.Builder().url(mUrl).build();
                    //发送请求newCall方法
                    Call call = okHttpClient.newCall(request);
                    //通过call去处理给你响应Response
                    Response response = call.execute();
                    //从相应体里面拿到数据
                    String string = response.body().string();
                    Log.e("string", string);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();			
    }

    //同步处理POST方式
    private void sendPost() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //1:学什么都能new出一个对象来
                    OkHttpClient okHttpClient = new OkHttpClient();
                    //创建请求体
                    RequestBody requestBody = new FormBody.Builder()
                            .add("mobile", "18513426687")
                            .add("password", "123456")
                            .build();
                    //Request就是请求的类
                    Request request = new Request.Builder().url(mPostUrl).post(requestBody).build();
                    //发送请求newCall方法
                    Call call = okHttpClient.newCall(request);
                    //通过call去处理给你响应Response
                    Response response = call.execute();
                    final String string = response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //异步的Get方式
    private void asyncSend() {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder().url(mUrl).build();
        Call call = okHttpClient.newCall(request);
        //异步处理
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure", "onFailure");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String string = response.body().string();
//                Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
                //一个小知识 不建议使用 在子线程直接刷新UI操作
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    //异步POST 我的微信号 lvxx18513426687
    private void asyncPost() {
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody body = new FormBody.Builder()
                .add("mobile", "18513426687")
                .add("password", "123456").build();
        //链式调用
        Request request = new Request.Builder().url(mPostUrl).post(body).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure", "onFailure");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String string = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    //下边的代码都采用工具类调用
    private void utilsGet() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final String jsonStr = OkHttpUtils.getInstance().get(mUrl);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, jsonStr, Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

展开阅读全文

没有更多推荐了,返回首页