美文网首页
OkHttp3使用

OkHttp3使用

作者: 今天天气很好嗯 | 来源:发表于2017-11-13 12:26 被阅读0次

OkHttp3使用

1、OkHttp的github地址:github地址

2、导入项目中

导入库

3、写请求  get使用

String url = "http://192.168.0.102:8080/ssDemo/user/test";

OkHttpClient okHttpClient = new OkHttpClient();

Request request = new Request.Builder() .url(url) .build();

Call call = okHttpClient.newCall(request);

// Response response = call.execute();

call.enqueue(new Callback() {

         @Override

         public void onFailure(Call call, IOException e) {

                   System.out.println("返回数据"+e);

                  Log.e("getRequest", "getRequest: 错误");

         }

        @Override

         public void onResponse(Call call, Response response) throws IOException {

                 System.out.println("返回数据"+response.body().string());

                 Log.e("getRequest", "getRequest: 返回数据");

         }

 });

4、post请求

String url = "http://192.168.0.102:8080/ssDemo/user/findUserById";

OkHttpClient okHttpClient = new OkHttpClient();

RequestBody body = new FormBody.Builder()

                       .add("id","1")

                       .build();

Request request = new Request.Builder() .url(url)

                       .post(body)

                        .build();

Call call = okHttpClient.newCall(request);

 call.enqueue(new Callback() {

                  @Override

                  public void onFailure(Call call, IOException e) {

                           System.out.println("返回数据"+e);

                           Log.e("getRequest", "getRequest: 错误");

                  }

                @Override

                 public void onResponse(Call call, Response response) throws IOException {

                                System.out.println("返回数据"+response.body().string());

                                Log.e("getRequest", "getRequest: 返回数据");

                 }

      });

相关文章

网友评论

      本文标题:OkHttp3使用

      本文链接:https://www.haomeiwen.com/subject/qixzmxtx.html