• Android 网络编程(一)


    概述

    一。Android平台网络相关API接口

      1.java.net.*(标准Java接口)

        java.net.*提供与联网有关的类,包括流、数据包套接字(socket)、Internet协议、常见Http处理等。比如:创建URL,以及URLConnection/HttpURLConnection对象、设置链接参数、链接到服务器、向服务器写数据、从服务器读取数据等通信。这些在Java网络编程中均有涉及。

      

      2.org.apache 接口

        

        对于大部分应用程序而言JDK本身提供的网络功能已远远不够,这时就需要Android提供的Apache HttpClient了。它是一个开源项目,功能更加完善,为客户端的Http编程提供高效、最新、功能丰富的工具包支持。

      3.Android.net.*(Android网络接口)

        常常使用此包下的类进行Android特有的网络编程,如:访问WiFi,访问Android联网信息,邮件等功能。

    二。服务器端返回客户端的内容有三种方式

      

      1.以HTML代码的形式返回。

      2.以XML字符串的形式返回,做Android开发时这种方式比较多。返回的数据需要通过XML解析(SAX、DOM,Pull,等)器进行解析(必备知识)。

      3.以json对象的方式返回。

     

    封装的工具类

    •    发送GET请求;
    •    发送POST请求;
    •    发送文件上传请求;
    •  发送XML数据;
      1 package com.kest.util;
      2 
      3 import java.io.BufferedReader;
      4 import java.io.ByteArrayOutputStream;
      5 import java.io.InputStream;
      6 import java.io.InputStreamReader;
      7 import java.io.OutputStream;
      8 import java.net.HttpURLConnection;
      9 import java.net.InetAddress;
     10 import java.net.Socket;
     11 import java.net.URL;
     12 import java.net.URLConnection;
     13 import java.net.URLEncoder;
     14 import java.util.Map;
     15 
     16 /**
     17  * 
     18  *
     19  *         (1)发送GET请求;
     20  * 
     21  *         (2)发送POST请求;
     22  * 
     23  *         (3)发送文件上传请求;
     24  * 
     25  *         (4)发送XML数据;
     26  */
     27 
     28 public class HttpRequestUtil {
     29     /**
     30      * 发送GET请求
     31      * 
     32      * @param url
     33      * @param params
     34      * @param headers
     35      * @return URLConnection
     36      * @throws Exception
     37      */
     38     public static URLConnection sendGetRequest(String url,
     39             Map<String, String> params, Map<String, String> headers)
     40             throws Exception {
     41         StringBuilder sb = new StringBuilder(url);
     42         // 如果是GET请求,则请求参数在URL中
     43         if (params != null && !params.isEmpty()) {
     44             sb.append("?");
     45             for (Map.Entry<String, String> entry : params.entrySet()) {
     46                 sb.append(entry.getKey()).append("=")
     47                         .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
     48                         .append("&");
     49             }
     50             sb.deleteCharAt(sb.length() - 1);
     51         }
     52         URL url1 = new URL(sb.toString());
     53         HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
     54         conn.setRequestMethod("GET");
     55         // 设置请求头
     56         if (headers != null && !headers.isEmpty()) {
     57             for (Map.Entry<String, String> entry : headers.entrySet()) {
     58                 conn.setRequestProperty(entry.getKey(), entry.getValue());
     59             }
     60         }
     61         conn.getResponseCode();
     62         return conn;
     63     }
     64 
     65     /**
     66      * 发送POST请求
     67      * 
     68      * @param url
     69      * @param params
     70      * @param headers
     71      * @return URLConnection
     72      * @throws Exception
     73      */
     74     public static URLConnection sendPostRequest(String url,
     75             Map<String, String> params, Map<String, String> headers)
     76             throws Exception {
     77         StringBuilder sb = new StringBuilder();
     78         // 如果存在参数,则放在HTTP请求体,形如name=aaa&age=10
     79         if (params != null && !params.isEmpty()) {
     80             for (Map.Entry<String, String> entry : params.entrySet()) {
     81                 sb.append(entry.getKey()).append("=")
     82                         .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
     83                         .append("&");
     84             }
     85             sb.deleteCharAt(sb.length() - 1);
     86         }
     87         URL url1 = new URL(url);
     88         HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
     89         conn.setRequestMethod("POST");
     90         conn.setDoOutput(true);
     91         OutputStream out = conn.getOutputStream();
     92         out.write(sb.toString().getBytes("UTF-8"));
     93         if (headers != null && !headers.isEmpty()) {
     94             for (Map.Entry<String, String> entry : headers.entrySet()) {
     95                 conn.setRequestProperty(entry.getKey(), entry.getValue());
     96             }
     97         }
     98         conn.getResponseCode(); // 为了发送成功
     99         return conn;
    100     }
    101 
    102     /**
    103      * 直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能: <FORM METHOD=POST
    104      * ACTION="http://192.168.0.200:8080/ssi/fileload/test.do"
    105      * enctype="multipart/form-data"> <INPUT TYPE="text" NAME="name"> <INPUT
    106      * TYPE="text" NAME="id"> <input type="file" name="imagefile"/> <input
    107      * type="file" name="zip"/> </FORM>
    108      * 
    109      * @param path
    110      *            
    111      * @param params
    112      *            请求参数 key为参数名,value为参数值
    113      * @param file
    114      *            上传文件
    115      */
    116     public static boolean uploadFiles(String path, Map<String, String> params,
    117             FormFile[] files) throws Exception {
    118         final String BOUNDARY = "---------------------------7da2137580612"; // 数据分隔线
    119         final String endline = "--" + BOUNDARY + "--\r\n";// 数据结束标志
    120 
    121         int fileDataLength = 0;
    122         if (files != null && files.length != 0) {
    123             for (FormFile uploadFile : files) {// 得到文件类型数据的总长度
    124                 StringBuilder fileExplain = new StringBuilder();
    125                 fileExplain.append("--");
    126                 fileExplain.append(BOUNDARY);
    127                 fileExplain.append("\r\n");
    128                 fileExplain.append("Content-Disposition: form-data;name=\""
    129                         + uploadFile.getParameterName() + "\";filename=\""
    130                         + uploadFile.getFilname() + "\"\r\n");
    131                 fileExplain.append("Content-Type: "
    132                         + uploadFile.getContentType() + "\r\n\r\n");
    133                 fileExplain.append("\r\n");
    134                 fileDataLength += fileExplain.length();
    135                 if (uploadFile.getInStream() != null) {
    136                     fileDataLength += uploadFile.getFile().length();
    137                 } else {
    138                     fileDataLength += uploadFile.getData().length;
    139                 }
    140             }
    141         }
    142         StringBuilder textEntity = new StringBuilder();
    143         if (params != null && !params.isEmpty()) {
    144             for (Map.Entry<String, String> entry : params.entrySet()) {// 构造文本类型参数的实体数据
    145                 textEntity.append("--");
    146                 textEntity.append(BOUNDARY);
    147                 textEntity.append("\r\n");
    148                 textEntity.append("Content-Disposition: form-data; name=\""
    149                         + entry.getKey() + "\"\r\n\r\n");
    150                 textEntity.append(entry.getValue());
    151                 textEntity.append("\r\n");
    152             }
    153         }
    154         // 计算传输给服务器的实体数据总长度
    155         int dataLength = textEntity.toString().getBytes().length
    156                 + fileDataLength + endline.getBytes().length;
    157 
    158         URL url = new URL(path);
    159         int port = url.getPort() == -1 ? 80 : url.getPort();
    160         Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);
    161         OutputStream outStream = socket.getOutputStream();
    162         // 下面完成HTTP请求头的发送
    163         String requestmethod = "POST " + url.getPath() + " HTTP/1.1\r\n";
    164         outStream.write(requestmethod.getBytes());
    165         String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";
    166         outStream.write(accept.getBytes());
    167         String language = "Accept-Language: zh-CN\r\n";
    168         outStream.write(language.getBytes());
    169         String contenttype = "Content-Type: multipart/form-data; boundary="
    170                 + BOUNDARY + "\r\n";
    171         outStream.write(contenttype.getBytes());
    172         String contentlength = "Content-Length: " + dataLength + "\r\n";
    173         outStream.write(contentlength.getBytes());
    174         String alive = "Connection: Keep-Alive\r\n";
    175         outStream.write(alive.getBytes());
    176         String host = "Host: " + url.getHost() + ":" + port + "\r\n";
    177         outStream.write(host.getBytes());
    178         // 写完HTTP请求头后根据HTTP协议再写一个回车换行
    179         outStream.write("\r\n".getBytes());
    180         // 把所有文本类型的实体数据发送出来
    181         outStream.write(textEntity.toString().getBytes());
    182         // 把所有文件类型的实体数据发送出来
    183         if (files != null && files.length != 0) {
    184             for (FormFile uploadFile : files) {
    185                 StringBuilder fileEntity = new StringBuilder();
    186                 fileEntity.append("--");
    187                 fileEntity.append(BOUNDARY);
    188                 fileEntity.append("\r\n");
    189                 fileEntity.append("Content-Disposition: form-data;name=\""
    190                         + uploadFile.getParameterName() + "\";filename=\""
    191                         + uploadFile.getFilname() + "\"\r\n");
    192                 fileEntity.append("Content-Type: "
    193                         + uploadFile.getContentType() + "\r\n\r\n");
    194                 outStream.write(fileEntity.toString().getBytes());
    195                 if (uploadFile.getInStream() != null) {
    196                     byte[] buffer = new byte[1024];
    197                     int len = 0;
    198                     while ((len = uploadFile.getInStream()
    199                             .read(buffer, 0, 1024)) != -1) {
    200                         outStream.write(buffer, 0, len);
    201                     }
    202                     uploadFile.getInStream().close();
    203                 } else {
    204                     outStream.write(uploadFile.getData(), 0,
    205                             uploadFile.getData().length);
    206                 }
    207                 outStream.write("\r\n".getBytes());
    208             }
    209         }
    210         // 下面发送数据结束标志,表示数据已经结束
    211         outStream.write(endline.getBytes());
    212         BufferedReader reader = new BufferedReader(new InputStreamReader(
    213                 socket.getInputStream()));
    214         if (reader.readLine().indexOf("200") == -1) {// 读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败
    215             return false;
    216         }
    217         outStream.flush();
    218         outStream.close();
    219         reader.close();
    220         socket.close();
    221         return true;
    222     }
    223 
    224     /**
    225      * 提交数据到服务器
    226      * 
    227      * @param path
    228      *            
    229      * @param params
    230      *            请求参数 key为参数名,value为参数值
    231      * @param file
    232      *            上传文件
    233      */
    234     public static boolean uploadFile(String path, Map<String, String> params,
    235             FormFile file) throws Exception {
    236         return uploadFiles(path, params, new FormFile[] { file });
    237     }
    238 
    239     /**
    240      * 将输入流转为字节数组
    241      * 
    242      * @param inStream
    243      * @return
    244      * @throws Exception
    245      */
    246     public static byte[] read2Byte(InputStream inStream) throws Exception {
    247         ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
    248         byte[] buffer = new byte[1024];
    249         int len = 0;
    250         while ((len = inStream.read(buffer)) != -1) {
    251             outSteam.write(buffer, 0, len);
    252         }
    253         outSteam.close();
    254         inStream.close();
    255         return outSteam.toByteArray();
    256     }
    257 
    258     /**
    259      * 将输入流转为字符串
    260      * 
    261      * @param inStream
    262      * @return
    263      * @throws Exception
    264      */
    265     public static String read2String(InputStream inStream) throws Exception {
    266         ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
    267         byte[] buffer = new byte[1024];
    268         int len = 0;
    269         while ((len = inStream.read(buffer)) != -1) {
    270             outSteam.write(buffer, 0, len);
    271         }
    272         outSteam.close();
    273         inStream.close();
    274         return new String(outSteam.toByteArray(), "UTF-8");
    275     }
    276 
    277     /**
    278      * 发送xml数据
    279      * 
    280      * @param path
    281      *            请求地址
    282      * @param xml
    283      *            xml数据
    284      * @param encoding
    285      *            编码
    286      * @return
    287      * @throws Exception
    288      */
    289     public static byte[] postXml(String path, String xml, String encoding)
    290             throws Exception {
    291         byte[] data = xml.getBytes(encoding);
    292         URL url = new URL(path);
    293         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    294         conn.setRequestMethod("POST");
    295         conn.setDoOutput(true);
    296         conn.setRequestProperty("Content-Type", "text/xml; charset=" + encoding);
    297         conn.setRequestProperty("Content-Length", String.valueOf(data.length));
    298         conn.setConnectTimeout(5 * 1000);
    299         OutputStream outStream = conn.getOutputStream();
    300         outStream.write(data);
    301         outStream.flush();
    302         outStream.close();
    303         if (conn.getResponseCode() == 200) {
    304             return read2Byte(conn.getInputStream());
    305         }
    306         return null;
    307     }
    308 }
  • 相关阅读:
    全程软件测试_项目启动
    全程软件测试_规范测试过程
    python_json常用的方法
    python_eval的用法
    python_判断字符串编码的方法
    python_Notepad++编码集的说明
    python_编码集的介绍
    初识HTML
    mysql学习目录
    python学习目录
  • 原文地址:https://www.cnblogs.com/kest/p/5021573.html
Copyright © 2020-2023  润新知