Okhttp使用
2016-04-30 09:57
393 查看
从网络中获取数据
activity_main.xml
MainActivity.java
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); } } }
相关文章推荐
- android网络通信之WIFI教程实例汇总
- git使用ssh密钥和https两种认证方式汇总(转)
- 机器学习之神经网络模型-下(Neural Networks: Representation)
- 机器学习之神经网络模型-上(Neural Networks: Representation)
- Android开发本地及网络Mp3音乐播放器(十一)使用Jsoup组件请求网络,并解析音乐数据
- Android开发本地及网络Mp3音乐播放器(十一)使用Jsoup组件请求网络,并解析音乐数据
- 安卓APP测试之使用Burp Suite实现HTTPS抓包方法
- java发送http的get,post请求【学习记录】(转)
- [置顶] linux TCP 和 socket 参数设置
- Android 网络请求方法
- 借助IP和网红的逻辑,网络文学江湖中免费与付费也能共生
- 扫黄打非办再行动,色情网络直播平台遭整治
- jmeter Http Request
- 移动网络的访问
- 如何在asp.net mvc3中使用HttpStatusCode
- 3月23日作业
- AFNetworking 3.0 使用详解和源码剖析
- UDP、TCP、socket区别
- UDP、TCP、socket区别
- BP神经网络介绍