Okhttp使用

来源:互联网 发布:黑龙江网络骗局 编辑:程序博客网 时间:2024/05/17 06:15

从网络中获取数据

这里写图片描述

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <TextView        android:id="@+id/tv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="xx"        />    <Button        android:id="@+id/btn"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/tv"        android:layout_margin="20dp"        android:text="Button"/></RelativeLayout>

MainActivity.java

package com.app.okhttptest;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import com.squareup.okhttp.OkHttpClient;import com.squareup.okhttp.Request;import com.squareup.okhttp.Response;import java.io.IOException;public class MainActivity extends AppCompatActivity implements View.OnClickListener{    private OkHttpClient client;    private Request request;    private Response response;    private TextView textView;    private Button btn;    private Handler mHandler = new Handler(){        @Override        public void handleMessage(Message msg) {            String info = (String) msg.obj;            textView.setText(info);        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        textView = (TextView) findViewById(R.id.tv);        btn = (Button) findViewById(R.id.btn);        btn.setOnClickListener(this);    }    @Override    public void onClick(View v) {        Thread thread = new Thread(new Task());        thread.start();    }    class Task implements Runnable{        @Override        public void run() {            client = new OkHttpClient();            request = new  Request.Builder().url("http://www.baidu.com").build();            Message msg = new Message();            try {                response = client.newCall(request).execute();            } catch (IOException e) {                e.printStackTrace();            }            if(response.isSuccessful()){                String body = response.body().toString();                msg.obj = body;            }            mHandler.sendMessage(msg);        }    }}
0 0