Android简易实战教程--第四十七话《使用OKhttp回调方式获取网络信息》
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                Android简易实战教程--第四十七话《使用OKhttp回调方式获取网络信息》
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                在之前的小案例中寫過一篇使用HttpUrlConnection獲取網絡數據的例子。在OKhttp盛行的時代,當然要學會怎么使用它,本篇就對其基本使用做一個介紹,然后再使用它的接口回調的方式獲取相同的數據。因為它封裝的很好了,并不需要我們去做封裝,只需要寫少量的代碼就可以獲取到復雜的網絡數據了。
一、OKhttp的最基本使用。
還是直接使用代碼來說話:
1、添加依賴:
Github網址:https://github.com/square/okhttp
compile 'com.squareup.okhttp3:okhttp:3.5.0'
2、等待構建成功后:在主活動中直接使用它的API
1、創建布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/send_request" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Send Request" /> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/response" android:layout_width="match_parent" android:layout_height="wrap_content" /> </ScrollView> </LinearLayout>
2、主活動中的代碼:
public class MainActivity extends Activity implements View.OnClickListener {private Button sendRequest;
    private TextView responseText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response);
        sendRequest.setOnClickListener(this);
    }@Override
    public void onClick(View v) {if (v.getId() == R.id.send_request) {sendRequestWithOKHttp();
        }}private void sendRequestWithOKHttp() {// 開啟線程來發起網絡請求
        new Thread(new Runnable() {@Override
            public void run() {try {OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("http://www.baidu.com").build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    show(responseData);
                } catch (IOException e) {e.printStackTrace();
                }}}).start();
    }public void show(final String finalDatas){runOnUiThread(new Runnable() {@Override
            public void run() {responseText.setText(finalDatas);
            }});
    }}
這樣我們就成功獲取到了網絡的數據,運行程序我們可以看到:
二、使用OKhttp提供的接口回調
1、定義一個HttpUtils類。加入如下靜態方法:
//使用OKhttp,OKhttp給封裝好了回調,我們直接使用即可 public static void sendOKHttpRequst(final String address, final okhttp3.Callback callback){new Thread(new Runnable() {@Override public void run() {OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(address).build(); client.newCall(request).enqueue(callback); }}).start(); }
2、使用工具類,使用回調方法
//使用OKhttp工具類 findViewById(R.id.btn_okhttp).setOnClickListener(new View.OnClickListener() {@Override public void onClick(View v) {HttpUtils.sendOKHttpRequst(address, new Callback() {@Override public void onFailure(Call call, IOException e) {//對異常情況處理 Log.e("MainActivity","錯誤信息是" + e.toString()); }@Override public void onResponse(Call call, final Response response) throws IOException {//得到服務器返回的數據response runOnUiThread(new Runnable() {@Override public void run() {try {mTextView.setText(response.body().string()); } catch (IOException e) {e.printStackTrace(); }}}); }}); }}); }
這里只需要給出主活動的代碼即可~,因為封裝的太好,我們只需要幾行代碼就可以完成功能。還需要注意的是,谷歌工程師給封裝業務邏輯是在子線程執行的,因此我們要更新數據要在主線程執行。運行程序接口是一樣的~
喜歡我的朋友可以關注我,本專欄不定期更新簡單有趣的安卓小文~
對于OKHttp更高級的用法,以后會在Android Studio精彩案例專欄里面進行細致詳細的分析
轉載于:https://www.cnblogs.com/wanghang/p/6299475.html
總結
以上是生活随笔為你收集整理的Android简易实战教程--第四十七话《使用OKhttp回调方式获取网络信息》的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: CSSOM之getComputedSty
- 下一篇: Android JNI编程(三)——C语
