1.增加开源库的支持
compile 'com.squareup.okhttp3:okhttp:3.4.1'2。在MianActivity中添加
package com.example.administrator.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity implements View.OnClickListener { TextView responseText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button sendRequest = (Button)findViewById(R.id.send_request); responseText = (TextView)findViewById(R.id.response_text); sendRequest.setOnClickListener(this); } public void onClick(View v){ if(v.getId() == R.id.send_request){ sendRequestWithOkHttp(); } } private void sendRequestWithOkHttp(){ new Thread(new Runnable() { @Override public void run() { try{ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("http://www.baidu.com").build(); Response response = client.newCall(request).execute(); String responseData = response.body().string(); showResponse(responseData.toString()); }catch (Exception e){ e.printStackTrace(); } } }).start(); } private void showResponse(final String response){ runOnUiThread(new Runnable() { @Override public void run() { responseText.setText(response); } }); } }
3。在Activity_main中添加
<LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <Button android:id="@+id/send_request" android:text="Send Request" android:layout_width="match_parent" android:layout_height="wrap_content" /> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/response_text" android:layout_width="match_parent" android:layout_height="wrap_content" /> </ScrollView> </LinearLayout>4.配置网络权限
<uses-permission android:name="android.permission.INTERNET" />