okhttp基本用法一get/post

8495 ワード

okhttpは1つのとても優秀なネットのフレームワークで、特徴のネットの上で検索してあって、もう贅沢に言わないで、この1篇はokhttpがどのように使うことを見ます
okhttpソースのダウンロードアドレスは次のとおりです.https://github.com/square/okhttp
この例のダウンロードアドレス:https://github.com/cmyeyi/NetFramework
現在のバージョンは3.11です.0(2018年8月13日)
とても簡単に使えます
1、依存ライブラリの導入
在build.gradleに追加
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
, External Libraries okhttp okio jar。 
2、okhttpを使用して非同期呼び出しを実践する
2.1、get非同期要求
/**
 *   okhttp get  
 */
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                ,          
            mHandler.sendMessage(message);
            Log.d(TAG, "response: " + message.obj.toString());
        }
    });

}

結果:
response: {"success":"0","msgid":"1000555","msg":"Parameter appkey or sign invalid."}
 
2.2、post非同期要求
/**
 *   okhttp post  
 */
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                ,          
            mHandler.sendMessage(message);
            Log.d(TAG, "response: " + message.obj.toString());
        }
    });

}

リクエスト結果:(フォーマット後)[success]:[1],[result]:[{"weaid":[1],[week]:[月曜日],[cityno]:[beijing],[citynm]:[北京],[cityid]:[101010100],[uptime]:[2018-08-13 00:30:00],[temperature]:[25℃],[humidity]:[98%],[aqi]:[53],[weather]:[陰],[weather_icon]:[http://api.k780.com/upload/weather/d/2.gif","wind":"南西风","winp":"1级","temp":"25","weatid":","windid":","16","winpid":","201","weather_iconid",",{"weaid":","week","月曜日","cityno","beijing","citynm":"北京","cityid":"101010100",『uptime』:『2018-08-13 02:30:00』,『temperature』:『25℃』,『humidity』:『98%』,『aqi』:『42』,『weather』:『夕立』,『weather_icon』:『http://api.k780.com/upload/weather/d/3.gif","wind":"風","winp":"0級","temp":"25","weatid":"4","windid":"423","winpid":"207","weather_iconid":"3"}}
2.3.json形式のpost非同期要求(サービス側がjson形式の要求をサポートする必要がある)
/**
 *     okhttp post  ,              
 */
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                ,          
            mHandler.sendMessage(message);
            Log.d(TAG, "response: " + message.obj.toString());
        }
    });
}

要求結果:
response: {"success":"0","msgid":"1000555","msg":"Parameter appkey or sign invalid."}
 
3、okhttp実践同期呼び出しを使用する
get、postリクエストの同期呼び出し方式、以下のコードのように、この方式は別のスレッド呼び出し、ネットワークリクエストが必要であることに注意してください.
/**
 *     okhttp get  ,              
 */
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);
    }

}


/**
 *     okhttp post  ,              
 */
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);
    }

}

スレッド呼び出しを別にします.そうしないと、エラーが発生します.
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();