android network 3 okhttp (1) get / Post basic usage

Posted by magicdanw on Wed, 01 Jan 2020 08:35:45 +0100

Okhttp is a very excellent network framework, with the characteristics of searching on the network, so we will not go over it again. This article will see how to use okhttp

The download address of okhttp source code is: https://github.com/square/okhttp

Sample download address of this article: https://github.com/cmyeyi/NetFramework.git

The current version is 3.11.0 (August 13, 2018)

It's very easy to use

1. Introduce dependency Library

Add to build.gradle

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

The following picture:
After joining successfully, you will see two jar s okhttp and okio under External Libraries.

 

2. Practice get method

/**
 * Test the get method of okhttp
 */
private void testOkhttpGet() {
    String url = "http://api.k780.com/?app=weather.history";
    okhttp3.Request request = new okhttp3.Request.Builder().url(url).get().build();
    OkHttpClient okHttpClient = new OkHttpClient();
    final Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Message message = Message.obtain();
            message.what = 0;
            message.obj = e.getMessage();
            mHandler.sendMessage(message);
            Log.d(TAG, "onFailure: " + message.obj.toString());
        }

        @Override
        public void onResponse(Call call, okhttp3.Response response) throws IOException {
            Message message = Message.obtain();
            message.what = 1;
            message.obj = response.body().string();//string cannot be called twice. If it is called once, it will be closed. If it is called twice, an exception will be reported
            mHandler.sendMessage(message);
            Log.d(TAG, "response: " + message.obj.toString());
        }
    });

}

Results posted only:

response: {"success":"0","msgid":"1000555","msg":"Parameter appkey or sign invalid."}

 

3. Practice post method

/**
 * Test the post method of okhttp
 */
private void testOkhttpPost() {
    String url = "http://api.k780.com/?app=weather.history";//
    // &weaid=1&date=2018-08-13&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";

    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody body = new FormBody.Builder()
            .add("weaid", "1")
            .add("date", "2018-08-13")
            .add("appkey", "10003")
            .add("sign", "b59bc3ef6191eb9f747dd4e83c99f2a4")
            .add("format", "json")
            .build();

    okhttp3.Request request = new okhttp3.Request.Builder()
            .url(url)
            .post(body)
            .build();

    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Message message = Message.obtain();
            message.what = 0;
            message.obj = e.getMessage();
            mHandler.sendMessage(message);
            Log.d(TAG, "response: " + message.obj.toString());
        }

        @Override
        public void onResponse(Call call, okhttp3.Response response) throws IOException {
            Message message = Message.obtain();
            message.what = 1;
            message.obj = response.body().string();//string cannot be called twice. If it is called once, it will be closed. If it is called twice, an exception will be reported
            mHandler.sendMessage(message);
            Log.d(TAG, "response: " + message.obj.toString());
        }
    });

}

Request result: (formatted)
  "success": "1",
  "result": [
    {
      "weaid": "1",
"week": "Monday",
      "cityno": "beijing",
"citynm": "Beijing",
      "cityid": "101010100",
      "uptime": "2018-08-13 00:30:00",
      "temperature": "25℃",
      "humidity": "98%",
      "aqi": "53",
"weather": "Yin",
      "weather_icon": "http://api.k780.com/upload/weather/d/2.gif",
"Wind": "southwest wind",
"Winp": "level 1",
      "temp": "25",
      "weatid": "3",
      "windid": "16",
      "winpid": "201",
      "weather_iconid": "2"
    },
    {
      "weaid": "1",
"week": "Monday",
      "cityno": "beijing",
"citynm": "Beijing",
      "cityid": "101010100",
      "uptime": "2018-08-13 02:30:00",
      "temperature": "25℃",
      "humidity": "98%",
      "aqi": "42",
"weather": "showers",
      "weather_icon": "http://api.k780.com/upload/weather/d/3.gif",
"Wind": "wind",
"Winp": "level 0",
      "temp": "25",
      "weatid": "4",
      "windid": "423",
      "winpid": "207",
      "weather_iconid": "3"
    }
  ]
}

4. json format post requests

/**
 * To test the post method of synchronizing okhttp, we must start another thread when using it
 */
private void testOkhttpPostJson() {
    String url = "http://api.k780.com/?app=weather.history";//


    String json = "{\"format\":\"json\",\"weaid\":1,\"date\":\"2018-08-13\",\"appkey\":\"10003\",\"sign\":\"b59bc3ef6191eb9f747dd4e83c99f2a4\"}";
    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
    Request request = new Request.Builder().post(body).url(url).build();

    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Message message = Message.obtain();
            message.what = 0;
            message.obj = e.getMessage();
            mHandler.sendMessage(message);
            Log.d(TAG, "response: " + message.obj.toString());
        }

        @Override
        public void onResponse(Call call, okhttp3.Response response) throws IOException {
            Message message = Message.obtain();
            message.what = 1;
            message.obj = response.body().string();//string cannot be called twice. If it is called once, it will be closed. If it is called twice, an exception will be reported
            mHandler.sendMessage(message);
            Log.d(TAG, "response: " + message.obj.toString());
        }
    });
}

Request result:

response: {"success":"0","msgid":"1000555","msg":"Parameter appkey or sign invalid."}

 

5. In addition, there is another synchronous call method using get and post requests, such as the following code. Note that this method requires another thread call and network request

/**
 * To test the get method of synchronous okhttp, we must start another thread when using it
 */
private String testOkhttpGetSynchronized() throws IOException {
    String url = "http://api.k780.com/?app=weather.history";

    okhttp3.Request request = new okhttp3.Request.Builder().url(url).get().build();
    OkHttpClient okHttpClient = new OkHttpClient();
    Response response = okHttpClient.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }

}


/**
 * To test the post method of synchronizing okhttp, we must start another thread when using it
 */
private String testOkhttpPostSynchronized() throws IOException {
    String url = "http://api.k780.com/?app=weather.history";//
    // &weaid=1&date=2018-08-13&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";

    RequestBody body = new FormBody.Builder()
            .add("weaid", "1")
            .add("date", "2018-08-13")
            .add("appkey", "10003")
            .add("sign", "b59bc3ef6191eb9f747dd4e83c99f2a4")
            .add("format", "json")
            .build();

    okhttp3.Request request = new okhttp3.Request.Builder()
            .url(url)
            .post(body)
            .build();

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

}

Call another thread, otherwise an error is reported:

new Thread(new Runnable() {
    @Override
    public void run() {
        Message message = Message.obtain();
        try {
            String result = testOkhttpGetSynchronized();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}).start();
new Thread(new Runnable() {
    @Override
    public void run() {
        Message message = Message.obtain();
        try {
            String result = testOkhttpPostSynchronized();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}).start();

 

 

 

 

 

Topics: OkHttp JSON network github