1. 程式人生 > >【快速開發】OKhttp3+fastjson 網路資料的請求與解析

【快速開發】OKhttp3+fastjson 網路資料的請求與解析

第一步:專案新增依賴,新增相應的許可權

找到build.gradle

gradle:新增關鍵程式碼,進行專案依賴

compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okio:okio:1.7.0'
compile 'com.alibaba:fastjson:1.2.23'

AndroidManifest.xml中加入關鍵關鍵程式碼

許可權:

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

第二步:建立實體類

使用GsonFormat外掛一鍵生成實體類

GsonFormat外掛下載及使用:

下載:    AndroidStudio->File->Plugins->   搜尋"GsonFormat"  ->安裝完成後重啟AndroidStudio

使用:    建立類->快捷鍵   Alt+Ins  ->選擇則GsonFormat    ->   把需要解析的資料複製貼上進彈出框內 ->點選OK



第三步:從網路獲取json資料

private void getAsynHttp() {
    OkHttpClient mOkHttpClient = new OkHttpClient();
Request.Builder requestBuilder = new Request.Builder().url(url); //可以省略,預設是GET請求 requestBuilder.method("GET",null); Request request = requestBuilder.build(); Call mcall= mOkHttpClient.newCall(request); mcall.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d
(TAG, "onFailure: "); } @Override public void onResponse(Call call, Response response) throws IOException { String json = response.body().string(); Log.d(TAG, "onResponse:json " +json); } }); }

第四步:fastjson解析資料

CityBean cityBean = JSON.parseObject(json, TestBean.class);Log.d(TAG, "onResponse:cityBean " + cityBean);

是不是很簡單。。。。