android-Okhttp初步使用

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

  看着很简单吧。网上也有不少例子,这里只作一下简单的操做,不让本身落伍,不作深刻研究。用的时候再好学习下。框架

相关文章
相关标签/搜索