自從谷歌把android的請求框架換成Okhttp後,android開發人員對其的討論就變的愈來愈火熱,全部咱做爲一枚吊絲android程序員,也不能太落後,因此拿來本身研究一下,雖然目前項目開發用的不是okhttp,但本身提早看一點,仍是對提升開發技術有好處的。html
目前只要求會使用,先不要求對其原理全面的瞭解。java
首先,要使用Okhttp,要先導入兩個jar依賴包。Okhttp.jar(我目前用的是2.7.0)與okio.jar(目前1.6.0)到libs下,而後一陣噼啪build path,就好了.android
本例請求的是json數據(是天氣預報的json數據,你們沒事時也能夠用這個請求練手。),至於json數據的解析什麼的,就不作了,只請求下來,而後作一個展現就好了,別的都是很簡單的。哈哈哈哈。。。。程序員
好,下面直接上代碼,就是在一個佈局中,設置一個button.一個textview,當點擊button時,請求數據,而後展現到textview上。(本例要第二次請求才會展現到textview上,緣由很好分析。)json
layout佈局:網絡
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${relativePackage}.${activityClass}" > <Button android:id="@+id/bt_ok" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Okhttp請求網絡" android:gravity="center_horizontal" android:clickable="true" android:onClick="btOk" /> <TextView android:id="@+id/tv_ok" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/bt_ok" android:gravity="center_horizontal" /> </RelativeLayout>
下面的是邏輯代碼。app
package com.example.jwwokhttp; import java.io.IOException; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class OkhttpActivity extends Activity { private OkHttpClient client; private TextView tvOk; private Response response; private String responseOk; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_okhttp); initView(); } private void initView() { // TODO 初始化佈局 tvOk = (TextView) findViewById(R.id.tv_ok); } public void btOk(View v) throws IOException { new Thread(new Runnable() {
//由於網絡請求是耗時操做,因此要開啓一個子線程,放在子線程中請求。 @Override public void run() { LogUtil.debug(getClass(), "btOk::::::::::::::::::"); // TODO 在線程中請求網絡 client = new OkHttpClient();
//這裏就開始了,實例化對象,
String url = "http://www.weather.com.cn/adat/cityinfo/101190404.html";
//請求設置 Request request = new Request.Builder().url(url).build(); try { response = client.newCall(request).execute(); if (response.isSuccessful()) { // 返回數據 responseOk = response.body().string(); LogUtil.debug(getClass(), "網絡返回數據:::::::::::"+responseOk); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); tvOk.setText(responseOk+""); } }
看着很簡單吧。網上也有不少例子,這裏只作一下簡單的操做,不讓本身落伍,不作深刻研究。用的時候再好學習下。框架