1.概述
在过去,Android上发送Http请求一般有两种方式:HttpURLConnection和HttpClient。不过由于HttpClient存在API数量过多,扩展困难等缺点,在Android6.0系统中,HttpClient就被完全移除了,标志着正式弃用。如下,将学习HttpURLConnection
2.HttpURLConnection
2.1 概述
HttpURLConnection是Java的标准类,用于Android程序进行网络请求。
2.2 获取HTTPURLConnection实例
一般需要new一个URL对象,并传入网络地址,然后调用openConnection()方法即可。如下所示:
try { URL url = new URL("http://www.baidu.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
2.3 设置请求方式
在获取到HttpURLConnection实例后,就可以设置Http请求所使用的方法了。常用的方法主要有:GET和POST。GET表示请求数据,POST表示提交数据。写法如下所示:
//GET connection.setRequestMethod("GET"); //POST connection.setRequestMethod("POST");
2.4 定制请求
比如设置连接超时,读取超时的毫秒数,服务器希望得到一些消息头等等,如下所示:
//设置连接超时为5秒 connection.setConnectTimeout(50000); //设置读取超时为5秒 connection.setReadTimeout(5000);
2.5 获取输入流
调用getInputStream()方法就可以获取到服务器返回的输入流,然后对输入流进行读取,如下所示:
//获取输入流 InputStream inputStream = connection.getInputStream();
2.6 关闭Http连接
调用disconnect()方法将Http连接关闭,如下所示:
//关闭Http连接 connection.disconnect();
3.Http的封装
Http的封装通过回调机制,代码如下所示:
1)回调接口
/** * Http回调接口 */ public interface HttpCallbackListener { //处理请求成功 void onFinish(String response); //处理请求失败 void onError(Exception e); }
2)HttpUtil
/** * Http工具类,利用回调机制 */ public class HttpUtil { /** * GET请求 * @param sendUrl * @param listener */ public static void requestUrlByGet(final String sendUrl, final HttpCallbackListener listener){ new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { URL url = new URL(sendUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); if (listener != null){ //利用回调机制 listener.onFinish(dealResponseResult(inputStream)); } } } catch (Exception e) { //异常处理 listener.onError(e); } finally { //关闭连接 connection.disconnect(); } } }).start(); } /** * POST请求 * @param sendUrl * @param params * @param listener */ public static void requestUrlByPost(final String sendUrl, final String params, final HttpCallbackListener listener){ new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { URL url = new URL(sendUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); //设置请求体的类型是文本类型 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //设置请求体的长度 connection.setRequestProperty("Content-Type", String.valueOf(params)); //获得输出流,向服务器写入数据 OutputStream outputStream = connection.getOutputStream(); outputStream.write(params.getBytes()); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); if (listener != null){ listener.onFinish(dealResponseResult(inputStream)); } } } catch (Exception e) { //异常处理 listener.onError(e); } finally { //关闭连接 connection.disconnect(); } } }).start(); } /** * 处理服务端返回的数据 * @param inputStream * @return String * @throws IOException */ public static String dealResponseResult(InputStream inputStream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer buffer = new StringBuffer(); String str = null; while ((str = reader.readLine()) != null) { buffer.append(str); } return buffer.toString(); } }
4.案例
下面案例以访问http://www.baidu.com网址,获取并展示返回的数据。
1)效果图
2)布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:orientation="vertical"> <Button android:id="@+id/send_request" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="send request"/> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/response_text" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </ScrollView> </LinearLayout>
3)逻辑业务
public class Main2Activity extends AppCompatActivity { private Button btnSendRequest; private TextView tvResponse; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); btnSendRequest = findViewById(R.id.send_request); tvResponse = findViewById(R.id.response_text); btnSendRequest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HttpUtil.requestUrlByGet("https://www.baidu.com", new HttpCallbackListener() { @Override public void onFinish(String response) { showResponseOnTextView(response); } @Override public void onError(Exception e) { e.printStackTrace(); } }); } }); } /** * 将获取到的数据展示在TextView控件上 * @param response */ private void showResponseOnTextView(final String response) { //切回主线程 runOnUiThread(new Runnable() { @Override public void run() { tvResponse.setText(response); } }); } }