您的位置:首页 > 理论基础 > 计算机网络

Okhttp使用

2016-04-30 09:57 393 查看
从网络中获取数据



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);

}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: