在使用OkHttp前,我們需要先導(dǎo)入OkHttp的第三方庫(kù)。
我們可以在Github上找到她的項(xiàng)目地址: https://github.com/square/okhttp
我們可以在Android Studio中使用Gradle, 最后效果如下:
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder() .url(requestUrl) .build();
requestUrl是一個(gè)字符串變量代表這個(gè)URL是為了JSON請(qǐng)求(The requestUrl is a String variable representing the Url for the JSON request.)
在這個(gè)測(cè)試中,我們將會(huì)使用如下的URl:http://iheartquotes.com/api/v1/random?format=json
Call call = okHttpClient.newCall(request);
Call對(duì)象會(huì)取走我們的 okHttpClient對(duì)象 和 我們的 request對(duì)象。
try{ Response response = call.execute(); if(response.isSuccessful()){ //The call was successful.print it to the log Log.v("OKHttp",response.body().string()); } }catch(IOException e){ e.printStackTrace();}
這是新手一個(gè)常見的錯(cuò)誤。在Android中不允許任何網(wǎng)絡(luò)的交互在主線程中進(jìn)行。It disallows it to force developers to use asynchronous callbacks.(能力有限這句話不敢強(qiáng)譯)。但是現(xiàn)在,我們的代碼看起來看起來十分的號(hào)好!下面我們來看看如何修復(fù)這個(gè)問題。
為了修補(bǔ)這個(gè)問題,我們只需要讓我們的Call執(zhí)行在非主線程內(nèi),所以利用一個(gè) asynchronous callback(異步的callBack)。
讓我們call異步的方法是通過調(diào)用我們Call對(duì)象的 enqueue()方法。
call.enqueue(new Callback()) { @Override public void onFailure( Request request, IOException e ) { } @Override public void OnResponse( Response response) throws IOException { try { if(response.isSuccessful()){ //The call was successful. print it to the log log.v("OKHttp",response.body.string()); } }catch (IOException e) { e.printStackTrace(); } }});
<uses-permission android:name="android.permission.INTERNET"/>
寫完后,瞬間爽朗起來。雖然還有問題。
http://www.skholingua.com/android-basic
https://github.com/square/okhttp/wiki/Recipes
聯(lián)系客服