码迷,mamicode.com
首页 > 移动开发 > 详细

Android常用开源库———————————OkHttp的使用方法

时间:2018-11-24 18:54:49      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:服务   需要   pos   col   cti   request对象   fail   run   uil   

OkHttp是一个优秀的网络通信库,GitHub项目主页地址

 

基本使用

在项目中中添加OkHttp库的依赖。.

implementation("com.squareup.okhttp3:okhttp:3.12.0")

 

OkHttp进行Get请求

//创建一个OkHttpClient的实例
OkHttpClient client = new OkHttpClient();
//创建一个Request对象
Request request = new Request.Builder().build;

//通过url()方法来设置目标的网络地址
Request request = new Request.Builder().url("http://www.baidu.com").build();
//调用newCall()方法来创建一个Call对象
Response response = client.newCall(request).exute();
//Response对象就是服务器返回的数据,通过如下写法得到返回的具体内容
String responseData = response.body().string()

 

OkHttp进行Post请求

//构建一个RequestBody对象存放待提交的参数
RequestBody requestBody = new FormBody.Builder().add("username","admin").add("password","12345").build();
//调用post()方法
Request request = new Request.Builder().uirl("http://www.baidu.com").post(requestBody).build();

接下来的操作和Get请求一样

 

同步请求时,需要开启子线程;异步请求时调用enqueue,无需开启子线程。

public class MainActivity extends AppCompatActivity  implements View.OnClickListener{

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button  sendRequest = (Button) findViewById(R.id.send_request);
        Button sendAsyncRequest = (Button) findViewById(R.id.send_asyncRequest);
        responseText = (TextView) findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
        sendAsyncRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_request:
                sendRequestWithOkHttp();
                break;

            case R.id.send_asyncRequest:
                sendAsyncRequestWithOkHttp();
                break;

            default:
                break;
        }
    }

    private void sendAsyncRequestWithOkHttp() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("http://www.baidu.com").build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(MainActivity.this,"get failed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String res = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        responseText.setText(res);
                    }
                });
            }
        });
    }


    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("http://www.baidu.com").build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(response);
            }
        });
    }
}

 

Android常用开源库———————————OkHttp的使用方法

标签:服务   需要   pos   col   cti   request对象   fail   run   uil   

原文地址:https://www.cnblogs.com/kyun/p/10012908.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!