码迷,mamicode.com
首页 > Web开发 > 详细

【框架】OkHttp

时间:2016-04-29 14:21:13      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

/**
 * *************************同步请求***************************
 * 1.创建OkHttpClient实例
 * 2.创建一个请求,设置请求地址
 * 3.调用Client的newCall方法获得一个Call对象
 * 4.调用call.execute();方法执行网络请求
 */
public class MainActivity extends AppCompatActivity {

    private OkHttpClient client;
    private TextView tv;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            tv.setText(msg.obj.toString());
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = ((TextView) findViewById(R.id.tv));
        client = new OkHttpClient();
    }

    //同步请求
    public void getData1(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Request request = new Request.Builder().url("http://www.baidu.com").build();
                Call call = client.newCall(request);
                try {
                    //发起网络请求
                    Response response = call.execute();
                    //获取网络请求结果
                    String string = response.body().string();
                    Message message = mHandler.obtainMessage();
                    message.obj = string;
                    message.what = 0;
                    mHandler.sendMessage(message);
                    Log.d("lenve", "getData1: " + string);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

 

【框架】OkHttp

标签:

原文地址:http://www.cnblogs.com/anni-qianqian/p/5445827.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!