android网络请求那点事

1 添加okhttp3依赖

在build.gradle中添加

compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okio:okio:1.9.0'

2 请求代码

具体请求步骤见代码中的注释

a 普通请求

// 创建请求客户端对象
OkHttpClient okHttpClient = new OkHttpClient();
// 创建表单
RequestBody formBody = new FormBody.Builder()
            .add("id", id)
            .add("type", type)
            .build();
// 创建请求对象
final Request request = new Request.Builder()
            .url(url)
            .post(formBody) // Get请求的话就不需要这一行了
            .build();
// 建立请求
Call call = okHttpClient.newCall(request);
// 接受响应
call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
                Log.e(TAG, "IOException: " + e);
        }
        @Override
        public void onResponse(Call call, Response response) throws IOException {
              // 使用Gson解析返回的数据
              Gson gson = new Gson();
              try {
                    String test = response.body().string();
                    Log.d(TAG, "json string: " + test);
                    Message message = gson.fromJson(test, Result.class);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
            }
});

b 通过OkHttpClient.Builder自定义client

如果我们想做一些事情,比如绕过SSL证书检测(参见我的另一篇博文) ,就需要我们对OkHttpClient做一些设置,直接看代码:

OkHttpClient okHttpClient = getUnsafeOkHttpClient().retryOnConnectionFailure(true).build();

上面我们通过调用一个方法返回的Builder创建OkHttpClient对象,方法如下:

public static OkHttpClient.Builder getUnsafeOkHttpClient() {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            return builder;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

可以看到可以在创建builder的过程中去做很多事情。

3 使用Gson解析Json数据

1) 添加项目依赖:

compile 'com.google.code.gson:gson:2.8.0'

2) 创建解析对象类:

根据返回数据的键值对创建类成员变量,注意类型。
比如返回

{
    "code": 123,
    "data": {
        "weather": "sunny",
        "temperature": 28,
    }
}

那就需要建两个类分别解析上面的两个对象,如:

public class Result {

    public int code;
    public Data data;

    public Message() {
    }
public class Data{
    public String weather;
    public int temperature;
}

3) Gson解析

String test = response.body().string();
Result result = gson.fromJson(test, Result.class);

注意response.body()只可取一次。

你可能感兴趣的:(android网络请求那点事)