3分钟
7.2实施步骤
实施步骤
1、activity_main.xml文件中添加一个”http获取数据”按钮和结果显示TextView。
表7-2-1 AndroidManifest.xml代码
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn_send"
android:text="HTTP获取数据"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="@+id/text_response"
app:layout_constraintTop_toBottomOf="@id/btn_send"/>
</android.support.constraint.ConstraintLayout>2、在文件MainActivity.java中添加如下代码:
表7-2-2MainActivity.java代码
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnSend;
private TextViewresponseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSend = findViewById(R.id.btn_send);
responseText= findViewById(R.id.text_response);
btnSend.setOnClickListener(MainActivity.this);
}
public void onClick(View v) {
if (v.getId()==R.id.btn_send){
httpGetMsg();
}
}
private void httpGetMsg(){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL("https://www.baidu.com");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
InputStream in = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader .readLine())!=null){
response.append(line);
}
showResponse(response.toString());
}catch (Exception e){
e.printStackTrace();
}finally {
if (reader!=null){
try {
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (connection!=null){
connection.disconnect();
}
}
}
}).start();
}
private void showResponse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
responseText.setText(response);
}
});
}
}运行结果如下:
学员评价