在Android 6.0以后,官方建议的处理网络请求的方式是HttpURLConnection,而HTTPClient已经被废弃。下面我们就了解一下HttpURLConnection的基本实现方法。
首先创建httpconnectiondemo,先写一个能够展示请求到的数据的xml布局:activity_main。
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns: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="com.wang.httpconnectiondemo.MainActivity"> <TextView android:id="@+id/tvResponse" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:background="#aa33ff" android:padding="24dip" android:textColor="#ffffff" android:textSize="16sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
这个简单的布局可以展示服务器响应的数据。
然后在MainActivity 中完成网络请求的业务逻辑。
1 给控件tvResponse设置一个点击事件,触发网络请求。
2 在方法requestServerData()中发送请求:
首先创建一个子线程,来处理网络请求这个耗时操作,在这个子线程中创建HttpURLConnection对象,设置请求的各项属性。
3 将读取的数据展示在布局的控件 tvResponse中。
注意事项:请求完成后,要关闭HttpURLConnection对象:
connection.disconnect()
扫描二维码关注公众号,回复:
46669 查看本文章
package com.wang.httpconnectiondemo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class MainActivity extends AppCompatActivity { public static String URL_ADDR = "https://www.baidu.com/"; private static final String TAG = "MainActivity"; private TextView tvResponse; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvResponse = findViewById(R.id.tvResponse); tvResponse.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { requestServerData(); } }); } private void requestServerData() { new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; BufferedReader reader = null; try { URL url = new URL(URL_ADDR); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(3000); connection.setReadTimeout(3000); InputStream inputStream = connection.getInputStream(); //读取输入流 reader = new BufferedReader(new InputStreamReader(inputStream)); // StringBuilder builder = new StringBuilder(); String lens; while ((lens = reader.readLine()) != null) { builder.append(lens); }
//将读取的数据展示在布局中 showResponse(builder.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException 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 string) { Log.i(TAG, "showResponse:------ "+ string); runOnUiThread(new Runnable() { @Override public void run() { tvResponse.setText(string); } }); } }
在这个demo中,创建了一个子线程来处理网络请求,为了便于管理线程,在优化过程中可以使用线程池来管理线程。