/** * *************************同步请求*************************** * 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(); } }
时间: 2024-10-28 20:17:28