Android——OkHttp

1. 添加依赖

编辑app/build.gradle 文件,在dependencies 闭包中添加如下内容:

implementation 'com.squareup.okhttp3:okhttp:3.4.1'

添加依赖会自动下载两个库,一个是OkHttp库,一个是Okio库,后者是前者的通信基础。

2. 用法

private void sendRequestWithOkHttp(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()                        
                    .url("http://192.168.238.175/index2.xml")                          
                    .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseJSONWithJSONObject(responseData);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
  • 创建一个PkHttpClient的实例 OkHttpClient client = newOkHttpClient();
  • 创建一个Request请求对象 Request request = new Request.Builder().build();,这只是创建了一个空的Request对象,并没有什么实际作用,我们可以在最终的build() 方法之前连缀很多其他方法来丰富这个Request对象。
  • 之后调用OkHttpClient的newCall() 方法来创建一个Call对象,并调用它的execute() 方法来发送请求并获取服务器返回的数据 Response response = client.newCall(request).execute();
  • Response 对象就是服务器返回的数据了,我们可以使用如下写法来得到返回的具体内容 String responseData = response.body().string();

3. 发起POST请求

首先需要构建出一个RequestBody对象来存放待提交的参数:

RequestBody requestBody = new FormBody.Builder()
        .add("username","admin")
        .add("password","123456")
        .build():

然后在Request.Builder 中调用一下post() 方法,并将RequestBody对象传入:

Request request = new Request.Builder()
        .url("https://www.baidu.com")
        .post(requestBody)
        .build();

接下来就和GET请求一样了,调用execute() 方法来发送请求并获取服务器返回的数据即可。

猜你喜欢

转载自blog.csdn.net/qq_35008279/article/details/82016414