其他分享
首页 > 其他分享> > OkHttp的简单使用代码示例

OkHttp的简单使用代码示例

作者:互联网

一、引入依赖
法1、下载jar引入
法2、maven依赖

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>3.2.0</version>
</dependency>

法3、gradle依赖

compile 'com.squareup.okhttp3:okhttp:3.2.0'

补充:
别忘了网络权限:

<uses-permission android:name="android.permission.INTERNET" />

二、“四剑客”构成基本请求
“四剑客”指的是“OkHttpClient (连接)”、“Request (请求)”、“Response (响应)”、“Builder (附加信息)”
简单的GET请求代码:

OkHttpClient client = new OkHttpClient();       // 获得连接
String run(String url) throws IOException {     // 请求方法
    Request request = new Request.Builder().url(url).build();   // Request被Builder附加一些信息,如请求的url地址
    Response response = client.newCall(request).execute();      // Request被OkHttpClient执行,返回Response
    if (response.isSuccessful()) {      // 获取结果
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

简单的POST请求代码(相比GET多了body):

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();       // 同上
String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);  // 构建body
    Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();     // 同上。但是这里Builder多附加了body
    Response response = client.newCall(request).execute();      // 同上
    f (response.isSuccessful()) {       // 同上
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

通过POST方式把键值对数据传送到服务器的代码:

OkHttpClient client = new OkHttpClient();       // 同上
String post(String url, String json) throws IOException {
    RequestBody formBody = new FormEncodingBuilder()
    .add("platform", "android")
    .add("name", "bug")
    .add("subject", "XXXXXXXXXXXXXXX")
    .build();       // 新的“剑客”:RequestBody,和新的“剑客”FormEncodingBuilder,把键值对组装成Body,其实原理还是Builder构建附加信息

    Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();     // 同上

    Response response = client.newCall(request).execute();  // 同上
    if (response.isSuccessful()) {  // 同上
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

标签:body,示例,url,代码,Request,OkHttpClient,OkHttp,new,response
来源: https://blog.csdn.net/sadkhkuhkjasga/article/details/123093024