自從谷歌把android的請求框架換成Okhttp后,android開發人員對其的討論就變的越來越火熱,所有咱作為一枚吊絲android程序員,也不能太落后,所以拿來自己研究一下,雖然目前項目開發用的不是okhttp,但自己提前看一點,還是對提高開發技術有好處的。
目前只要求會使用,先不要求對其原理全面的了解。
首先,要使用Okhttp,要先導入兩個jar依賴包。Okhttp.jar(我目前用的是2.7.0)與okio.jar(目前1.6.0)到libs下,然后一陣噼啪build path,就行了.
本例請求的是json數據(是天氣預報的json數據,大家沒事時也可以用這個請求練手。),至於json數據的解析什么的,就不做了,只請求下來,然后做一個展示就行了,別的都是很簡單的。哈哈哈哈。。。。
好,下面直接上代碼,就是在一個布局中,設置一個button.一個textview,當點擊button時,請求數據,然后展示到textview上。(本例要第二次請求才會展示到textview上,原因很好分析。)
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>
下面的是邏輯代碼。
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+""); } }
看着很簡單吧。網上也有很多例子,這里只做一下簡單的操作,不讓自己落伍,不做深入研究。用的時候再好學習下。
