1. 程式人生 > >Android開發--與後臺通訊(一)--API資料獲取

Android開發--與後臺通訊(一)--API資料獲取

API網路請求

對於之前寫的2篇關於API的內容和JSON文字解析類,當然需要有著配套的網路請求配合安卓端請求和獲取資料,這篇部落格介紹與後臺通訊中網路的基本請求與API資料有關

  • 準備

    這裡我們使用現在封裝得比較好的包:okhttp
    在配置檔案中加入依賴:

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

    如圖:

    這裡寫圖片描述

  • 程式碼編寫

    首先很重要的一點:Android網路請求因為有延遲,必須要在多執行緒中進行

    先看一個整個的請求程式碼:

                    final String address  =  "http://route.showapi.com/268-1?showapi_appid=42305&keyword="
    + searchWord +"&proId=&cityId=&areaId=&page=&showapi_sign=c069130238404775894ba39caf3ac094"; mView = new CatLoadingView(); mView.show(getSupportFragmentManager(), ""); new Thread(new Runnable() { @Override public
    void run() { try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(address) .build(); Response
    response = client.newCall(request).execute(); responseData = response.body().string(); Message message = new Message(); message.what = UPDATE_TEXT; mHandler.sendEmptyMessage(message.what); } catch (IOException e) { e.printStackTrace(); } } }).start(); }

    可以看到:

    這裡的responseData就是網路請求返回的結果,接下來可以對這個結果進行一個JSON文字的解析

    同時可以看到:

    Message message = new Message();
    message.what = UPDATE_TEXT;
    mHandler.sendEmptyMessage(message.what);

    這是一個非同步訊息處理機制,剛才有說到,網路請求在子執行緒完成,如果想要做到在主執行緒做出一些修改UI的操作,就需要這個非同步訊息處理

    上面程式碼是訊息的發出,我們看一下訊息的獲取和相關操作:

    protected Handler mHandler =  new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case UPDATE_TEXT:
                        Log.e("responseData----",""+responseData);
                        Gson gs = new Gson();
    
                        entity= gs.fromJson(responseData,entityClass);
                        String code= entity.getShowapi_res_code();
                        SearchBodyEntity showapi_res_body = entity.getShowapi_res_body();
                        String retCode = showapi_res_body.getRet_code();
                        SearchBeanEntity pagebean = showapi_res_body.getPagebean();
                        Log.e("pagebean----",""+pagebean);
                        Log.e("pagebeangetAllPages----",""+pagebean.getAllPages());
                        Log.e("getContentList----",""+pagebean.getContentlist());
    
                        List<SearchListEntity> contentList = pagebean.getContentlist();
                        if (contentList.size() != 0) {
                            Log.e("contentList----", "" + contentList);
                            SearchListEntity[] contentlist_objects = new SearchListEntity[contentList.size()];
                            location[] locations = new location[contentList.size()];
                            String[] lons = new String[contentList.size()];
                            String[] lats = new String[contentList.size()];
                            String[] names = new String[contentList.size()];
                            String[] summarys = new String[contentList.size()];
                            String[] contents = new String[contentList.size()];
                            String[] attentions = new String[contentList.size()];
                            String[] opentimes = new String[contentList.size()];
                            String[] coupons = new String[contentList.size()];
                            String[] my_addresss = new String[contentList.size()];
                            String[] picture = new String[contentList.size()];
                            for (int i = 0; i < contentList.size(); i++) {
                                SearchListEntity contentlist_object = contentList.get(i);
                                contentlist_objects[i] = contentlist_object;
                                location location = contentlist_object.getLocation();
                                locations[i] = location;
                                String lon = location.getLon();
                                lons[i] = lon;
                                String lat = location.getLat();
                                lats[i] = lat;
                                String name = contentlist_object.getName();
                                names[i] = name;
                                String summary = contentlist_object.getSummary();
                                summarys[i] = summary;
                                String content = contentlist_object.getContent();
                                contents[i] = content;
                                String attention = contentlist_object.getAttention();
                                attentions[i] = attention;
                                String opentime = contentlist_object.getOpentime();
                                opentimes[i] = opentime;
                                String coupon = contentlist_object.getCoupon();
                                coupons[i] = coupon;
                                String my_address = contentlist_object.getAddress();
                                my_addresss[i] = my_address;
                                List<picList> picList = contentlist_object.getPicList();
                                picture[i] = picList.get(0).getPicUrl();
                                Log.e("", "" + picture[i]);
                            }
    
                            Intent intent = new Intent(SearchActivity.this, SearchDetailActivity.class);
                            intent.putExtra("name", names);
                            intent.putExtra("summary", summarys);
                            intent.putExtra("my_address", my_addresss);
                            intent.putExtra("opentime", opentimes);
                            intent.putExtra("picture", picture);
                            intent.putExtra("coupon", coupons);
                            intent.putExtra("attention", attentions);
                            intent.putExtra("content", contents);
                            intent.putExtra("lon", lons);
                            intent.putExtra("lat", lats);
                            mView.dismiss();
                            startActivity(intent);
                        }else {
                            Toast.makeText(SearchActivity.this,"查無結果",Toast.LENGTH_LONG).show();
                        }
                        break;
                }
            }
        };

    這裡對之前發出的訊息做的一個處理,包含介面之間的跳轉、JSON文字解析的操作

以上就是API資料獲取的部分內容,應該算是與後臺通訊最基本的內容