android-Okhttp初步使用

时间:2021-12-22 15:11:56

  自从谷歌把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+"");
}
}

  看着很简单吧。网上也有很多例子,这里只做一下简单的操作,不让自己落伍,不做深入研究。用的时候再好学习下。