一起学Android之Http访问

概述

在Android开发中,一般通过网络进行访问服务器端的信息(存储和检索网络中的数据),如API接口,WebService,网络图片等。今天主要讲解Http访问的常用方法,仅供学习分享使用。

涉及知识点

  1. URL 表示互联网位置的统一资源标识符。
  2. HttpURLConnection 表示一个URL的Http连接,是一个抽象类,通过URL中的 openConnection()实例化一个连接对象。
  3. setConnectTimeout(5000) 设置超时时间,setRequestMethod("GET") 设置访问方式。
  4. getResponseCode() 获取返回码,如200表示成功。
  5. getInputStream() 返回读取到数据的字节流; getOutputStream() 返回往指定URL写入数据的字节流。
  6. ByteArrayOutputStream 数组和输出流之间的转换。
  7. WebView 用于显示Web Page的一个控件,通过loadDataWithBaseURL(String baseUrl, String data,String mimeType, String encoding, String historyUrl)加载内容。

Http访问步骤

  1. 创建一个URL对象: URL url = new URL(https://www.baidu.com);
  2. 调用URL对象的openConnection( )来获取HttpURLConnection对象实例: HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  3. 设置HTTP请求使用的方法:GET或者POST,或者其他请求方式比如:PUT conn.setRequestMethod("GET");
  4. 设置连接超时,读取超时的毫秒数,以及服务器希望得到的一些消息头 conn.setConnectTimeout(6*1000); conn.setReadTimeout(6 * 1000);
  5. 调用getInputStream()方法获得服务器返回的输入流,然后输入流进行读取了 InputStream in = conn.getInputStream();
  6. 最后调用disconnect()方法将HTTP连接关掉 conn.disconnect();

示例图

如下图所示:

核心代码

获取数据类

 1 /**
 2  * Created by hex on 2019/4/6.
 3  */
 4 public class GetData {
 5     // 定义一个获取网络图片数据的方法:
 6     public static byte[] getImage(String path) throws Exception {
 7         URL url = new URL(path);
 8         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 9         // 设置连接超时为5秒
10         conn.setConnectTimeout(5000);
11         // 设置请求类型为Get类型
12         conn.setRequestMethod("GET");
13         // 判断请求Url是否成功
14         if (conn.getResponseCode() != 200) {
15             throw new RuntimeException("请求url失败");
16         }
17         InputStream inStream = conn.getInputStream();
18         byte[] bt = StreamTool.read(inStream);
19         inStream.close();
20         return bt;
21     }
22 
23     // 获取网页的html源代码
24     public static String getHtml(String path) throws Exception {
25         URL url = new URL(path);
26         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
27         conn.setConnectTimeout(5000);
28         conn.setRequestMethod("GET");
29         if (conn.getResponseCode() == 200) {
30             InputStream in = conn.getInputStream();
31             byte[] data = StreamTool.read(in);
32             String html = new String(data, "UTF-8");
33             return html;
34         }
35         return null;
36     }
37 }

InputStream转换为byte[]功能

 1 /**
 2  * Created by Administrator on 2019/4/6.
 3  */
 4 public class StreamTool {
 5     //从流中读取数据
 6     public static byte[] read(InputStream inStream) throws Exception {
 7         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
 8         byte[] buffer = new byte[1024];
 9         int len = 0;
10         while ((len = inStream.read(buffer)) != -1) {
11             outStream.write(buffer, 0, len);
12         }
13         inStream.close();
14         return outStream.toByteArray();
15     }
16 }

刷新界面赋值

 1 // 用于刷新界面
 2     private Handler handler = new Handler() {
 3         public void handleMessage(android.os.Message msg) {
 4             switch (msg.what) {
 5                 case 0x001:
 6                     hideAllWidget();
 7                     imgPic.setVisibility(View.VISIBLE);
 8                     imgPic.setImageBitmap(bitmap);
 9                     Toast.makeText(MainActivity.this, "图片加载完毕", Toast.LENGTH_SHORT).show();
10                     break;
11                 case 0x002:
12                     hideAllWidget();
13                     scroll.setVisibility(View.VISIBLE);
14                     txtshow.setText(detail);
15                     Toast.makeText(MainActivity.this, "HTML代码加载完毕", Toast.LENGTH_SHORT).show();
16                     break;
17                 case 0x003:
18                     hideAllWidget();
19                     webView.setVisibility(View.VISIBLE);
20                     webView.loadDataWithBaseURL("", detail, "text/html", "UTF-8", "");
21                     Toast.makeText(MainActivity.this, "网页加载完毕", Toast.LENGTH_SHORT).show();
22                     break;
23                 default:
24                     break;
25             }
26         }
27 
28         ;
29     };

如果要访问网络,还需要有相应的权限

1  <uses-permission android:name="android.permission.INTERNET" />

备注

关于Http访问的相关知识还有很多,本文知识简单粗略的讲解,希望抛砖引玉,共同学习。

猜你喜欢

转载自www.cnblogs.com/hsiang/p/10662616.html