開發實踐 | android網絡通信 接收和發送數據詳解

github:https://github.com/MichaelBeechan

CSDN:https://blog.csdn.net/u011344545

============================================================

一、從網絡上獲取數據(圖片、網頁、XML、JSON等)
1.從網絡獲取一張圖片,然後顯示在手機上
 

[java] view plaincopy

  1. public byte [] getImageFromNet(){  
  2.   try {  
  3.    URL url = new URL("http://img10.360buyimg.com/n1/4987/9dceed99-e710-4ca8-b7f1-4e9dc01a0f75.jpg");  
  4.    HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  5.    conn.setRequestMethod("GET");  
  6.    conn.setConnectTimeout(5 * 1000);  
  7.    conn.connect();  
  8.    InputStream inStream = conn.getInputStream();  
  9.    byte [] data = readInputStream(inStream);//獲取圖片的二進制數據  
  10.    //FileOutputStream outStream = new FileOutputStream("360buy.jpg");  
  11.    //outStream.write(data);  
  12.    //outStream.close();  
  13.    return data;  
  14.   } catch (Exception e) {  
  15.    e.printStackTrace();  
  16.   }   
  17.  }  
  18.  private byte [] readInputStream(InputStream inStream) throws IOException {  
  19.   ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();  
  20.   byte[] buffer = new byte[1024];  
  21.   int len = -1;  
  22.   while((len = inStream.read(buffer)) != -1){  
  23.    byteOutputStream.write(buffer, 0, len);  
  24.   }  
  25.   inStream.close();  
  26.   byte [] data = byteOutputStream.toByteArray();  
  27.   byteOutputStream.close();  
  28.   return data;  
  29.  }  

②使用ImageView組件顯示圖片。
 ③生成位圖並設置到ImageView中
 

[java] view plaincopy

  1. Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);  
  2.  imageView.setImageBitmap(bitmap);  

④在AndroidManifest.xml文件添加網絡訪問權限:

 

[java] view plaincopy

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

2.從網絡獲取指定網頁的html代碼,然後顯示在手機上

 

[java] view plaincopy

  1. public String getHtmlCodeFromNet(){  
  2.   try {  
  3.    URL url = new URL("http://www.163.com");  
  4.    HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  5.    conn.setRequestMethod("GET");  
  6.    conn.setConnectTimeout(5 * 1000);  
  7.    conn.connect();  
  8.    InputStream inStream = conn.getInputStream();  
  9.    byte [] data = readInputStream(inStream);  
  10.    String htmlString = new String(data, "gb2312");  
  11.    System.out.println(htmlString);  
  12.    return htmlString;  
  13.   } catch (Exception e) {  
  14.    e.printStackTrace();  
  15.   }   
  16.  }  

 ②使用TextView組件顯示網頁代碼
 ScrollView 滾動條

 

[java] view plaincopy

  1. <ScrollView  
  2.      android:layout_width="fill_parent"  
  3.     android:layout_height="fill_parent">  
  4.  <TextView   
  5.      android:layout_width="fill_parent"  
  6.      android:layout_height="wrap_content"  
  7.      android:id="@+id/textView"  
  8.      />  
  9.     </ScrollView>  

 ③在AndroidManifest.xml文件添加網絡訪問權限:

 

[java] view plaincopy

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

 

3.從服務器上獲取最新的視頻資訊信息,該信息以XML格式返回給Android客戶端,然後列表顯示在手機上。
 >>最新資訊
 喜羊羊與灰太狼      時長:60
 盜夢空間    時長:120
 生化危機             時長:100

 ①開發web端,在此採用Struts 2技術
 ②設計顯示界面,使用ListView
 ③開發Android手機視頻資訊客戶端
 注意:不能使用127.0.0.1或者localhost訪問在本機開發的web應用
 部分代碼:

[java] view plaincopy

  1. public List<Video> getXMLLastVideos(String urlPath) throws Exception{  
  2.  URL url = new URL(urlPath);  
  3.  HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  4.  conn.setRequestMethod("GET");  
  5.  conn.setConnectTimeout(5 * 1000);  
  6.  conn.connect();  
  7.  InputStream inStream = conn.getInputStream();  
  8.  return parseXML(inStream);  
  9. }  

 

 

[java] view plaincopy

  1. private List<Video> parseXML(InputStream inStream) throws Exception {  
  2.  List<Video> videos = null;  
  3.  Video video = null;    
  4.  XmlPullParser parser = Xml.newPullParser();  
  5.  parser.setInput(inStream, "UTF-8");  
  6.  int eventType = parser.getEventType();  
  7.  while(eventType != XmlPullParser.END_DOCUMENT){  
  8.   switch (eventType) {  
  9.    case XmlPullParser.START_DOCUMENT:  
  10.     videos = new ArrayList<Video>();  
  11.     break;  
  12.    case XmlPullParser.START_TAG:       
  13.     String name = parser.getName();  
  14.     if("video".equals(name)){  
  15.      video = new Video();  
  16.      video.setId(new Integer(parser.getAttributeValue(0)));  
  17.     }  
  18.     if(video != null){  
  19.      if("title".equals(name)){  
  20.       video.setTitle(parser.nextText());  
  21.      }else if("timeLength".equals(name)){  
  22.       video.setTimeLength(new Integer(parser.nextText()));  
  23.      }  
  24.     }  
  25.     break;  
  26.    case XmlPullParser.END_TAG:  
  27.     String pname = parser.getName();  
  28.     if("video".equals(pname)){  
  29.      videos.add(video);  
  30.      video = null;  
  31.     }  
  32.     break;  
  33.    default:  
  34.     break;  
  35.   }  
  36.   eventType = parser.next();  
  37.  }  
  38.  return videos;  
  39. }  

 ④在AndroidManifest.xml文件添加網絡訪問權限:

 

[java] view plaincopy

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

 


4.從服務器上獲取最新的視頻資訊信息,該信息以JSON格式返回給Android客戶端,然後列表顯示在手機上。
服務器端需要返回的JSON數據:

[java] view plaincopy

  1. [{id:1,title:"aaa1",timeLength:50},{id:2,title:"aaa2",timeLength:50},{id:3,title:"aaa3",timeLength:50}]  

 

 

[java] view plaincopy

  1. public List<Video> getJSONLastVideos(String urlPath) throws Exception{  
  2.  URL url = new URL(urlPath);  
  3.  HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  4.  conn.setRequestMethod("GET");  
  5.  conn.setConnectTimeout(5 * 1000);  
  6.  conn.connect();  
  7.  InputStream inStream = conn.getInputStream();  
  8.  byte [] data = StreamTools.readInputStream(inStream);  
  9.  String json = new String(data);  
  10.  JSONArray array = new JSONArray(json);  
  11.  List<Video> videos = new ArrayList<Video>();  
  12.  for(int i = 0;i < array.length(); i++){  
  13.   JSONObject item = array.getJSONObject(i);  
  14.   int id = item.getInt("id");  
  15.   String title = item.getString("title");  
  16.   int timeLength = item.getInt("timeLength");  
  17.   videos.add(new Video(id, title, timeLength));  
  18.  }  
  19.  return videos;  
  20. }  

 


二、通過HTTP協議提交文本數據(GET/POST)
GET、POST、HttpClient
1.通過GET方式提交參數給服務器:注意處理亂碼(Android系統默認編碼是UTF-8),提交的數據最大2K。
 ①服務器端代碼

[java] view plaincopy

  1. HttpServletRequest request = ServletActionContext.getRequest();  
  2. //服務器端編碼處理,先以ISO-8859-1編碼得到二進制數據,然後使用UTF-8對數據重新編碼  
  3. byte [] data = request.getParameter("title").getBytes("ISO-8859-1");  
  4. String titleString = new String(data, "UTF-8");  
  5. System.out.println("this.title==" + titleString);  
  6. System.out.println("this.timeLength==" + this.timeLength);  

 ②客戶端代碼

 

[java] view plaincopy

  1. public boolean sendGetRequest(String path, Map<String, String> params, String enc) throws Exception{  
  2.  StringBuilder sb = new StringBuilder(path);  
  3.  sb.append('?');  
  4.  if(params != null && !params.isEmpty()){  
  5.   for(Map.Entry<String, String> entry : params.entrySet()){  
  6.    sb.append(entry.getKey())  
  7.    .append('=')  
  8.    //對客戶端發送GET請求的URL重新編碼  
  9.    .append(URLEncoder.encode(entry.getValue(), enc))  
  10.    .append('&');  
  11.   }  
  12.   sb.deleteCharAt(sb.length()-1);  
  13.  }  
  14.  URL url = new URL(sb.toString());  
  15.  HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  16.  conn.setRequestMethod("GET");  
  17.  conn.setConnectTimeout(5 * 1000);  
  18.  if(conn.getResponseCode() == 200){  
  19.   return true;  
  20.  }  
  21.  return false;  
  22. }  

2.通過POST方式提交參數給服務器:
 ①<form method="post"/> 瀏覽器會把提交的數據轉換成Http協議
 
 ②分析Http協議(使用HttpWatch)
 第一部分:發送給服務器的
 請求頭部分(**********表示Http協議中必須提供的部分)

 

[java] view plaincopy

  1. POST /videoweb/managerPost.action HTTP/1.1---(請求方式 請求路徑 使用Http協議是1.1)  
  2. Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel,  
  3. application/vnd.ms-powerpoint, application/msword, application/QVOD, application/QVOD, */* ---(瀏覽器接收的數據類型)  
  4. Referer: http://127.0.0.1:8081/videoweb/index.jsp---(請求來源,即從哪個頁面發出請求的)  
  5. Accept-Language: zh-cn,en-US;q=0.5  
  6. User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; CIBA; .NET CLR 2.0.50727) ---(用戶的瀏覽器類型)  
  7. Content-Type: application/x-www-form-urlencoded ---(POST請求的內容類型)**********  
  8. Accept-Encoding: gzip, deflate  
  9. Host: 127.0.0.1:8081    ---(POST請求的服務器主機名和端口)**********  
  10. Content-Length: 46    ---(POST請求的內容長度,即實體數據部分的長度)**********  
  11. Connection: Keep-Alive    ---(長連接)  
  12. Cache-Control: no-cache  
  13. Cookie: JSESSIONID=EFD762A0997BE1191DABFC311B345EE7  

 實體數據部分

 

[java] view plaincopy

  1. title=aaa&timeLength=22&sub=%E6%8F%90%E4%BA%A4  

 
 第二部分:客戶端接收到的

 

[java] view plaincopy

  1. HTTP/1.1 200 OK  
  2. Server: Apache-Coyote/1.1  
  3. Content-Type: text/html;charset=UTF-8  
  4. Content-Length: 275  
  5. Date: Sun, 06 Mar 2011 10:57:55 GMT  
  6.   
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  8. <html>  
  9. <head>  
  10. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  11. <title>Insert title here</title>  
  12. </head>  
  13. <body>  
  14. 淇濆瓨瀹屾垚錛?  
  15. </body>  
  16. </html>  

 
 ③服務器端代碼

 

[java] view plaincopy

  1. HttpServletRequest request = ServletActionContext.getRequest();  
  2. request.setCharacterEncoding("UTF-8");  
  3. System.out.println("doPostRequest");  
  4. System.out.println("this.title==" + this.title);  
  5. System.out.println("this.timeLength==" + this.timeLength);  

 ④客戶端代碼

 

[java] view plaincopy

  1. public boolean sendPostRequest(String path, Map<String, String> params, String enc) throws Exception{  
  2.  //分析http協議  
  3.  //發出post請求時,瀏覽器會自動爲實體數據部分進行重新編碼。由於我們使用的是Android,沒有用IE瀏覽器,因此需要手動對URL重新編碼。  
  4.  //username=%E5%BC%A0%E4%B8%89&sub=%E7%99%BB%E9%99%86  
  5.  StringBuilder sb = new StringBuilder();  
  6.  if(params != null && !params.isEmpty()){  
  7.   for(Map.Entry<String, String> entry : params.entrySet()){  
  8.    sb.append(entry.getKey())  
  9.    .append('=')  
  10.    //對客戶端post請求的URL手動重新編碼  
  11.    .append(URLEncoder.encode(entry.getValue(), enc))  
  12.    .append('&');  
  13.   }  
  14.   sb.deleteCharAt(sb.length()-1);  
  15.  }  
  16.  URL url = new URL(path);  
  17.  HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  18.  conn.setRequestMethod("POST");  
  19.  conn.setConnectTimeout(5 * 1000);  
  20.  //如果通過post提交數據,必須設置允許對外輸出數據。  
  21.  conn.setDoOutput(true);  
  22.  //Content-Type: application/x-www-form-urlencoded  
  23.  //Content-Length: 46  獲取實體數據的二進制長度  
  24.  byte [] data = sb.toString().getBytes();  
  25.  //設置請求屬性  
  26.  conn.setRequestProperty("Content-Type""application/x-www-form-urlencoded");  
  27.  conn.setRequestProperty("Content-Length", String.valueOf(data.length));  
  28.  OutputStream outputStream = conn.getOutputStream();  
  29.  outputStream.write(data);  
  30.  outputStream.flush();  
  31.  outputStream.close();  
  32.  if(conn.getResponseCode() == 200){  
  33.   return true;  
  34.  }  
  35.  return false;  
  36. }  

3.使用HttpClient開源項目提交參數給服務器
 ①服務器端代碼

 

[java] view plaincopy

  1. HttpServletRequest request = ServletActionContext.getRequest();  
  2. request.setCharacterEncoding("UTF-8");  
  3. System.out.println("this.title==" + this.title);  
  4. System.out.println("this.timeLength==" + this.timeLength);  

 ②客戶端代碼

 

[java] view plaincopy

  1. public boolean sendRequestByHttpClient(String path, Map<String, String> params, String enc) throws Exception{  
  2.  //名值對  
  3.  List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();  
  4.  if(params != null && !params.isEmpty()){  
  5.   for(Map.Entry<String, String> entry : params.entrySet()){      
  6.    paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
  7.   }  
  8.  }  
  9.  //對實體數據進行重新編碼  
  10.  UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramPairs, enc);  
  11.  //相當於form  
  12.  HttpPost post = new HttpPost(path);  
  13.  post.setEntity(entity);  
  14.  //相當於客戶端瀏覽器  
  15.  DefaultHttpClient client = new DefaultHttpClient();  
  16.  //執行請求  
  17.  HttpResponse response = client.execute(post);  
  18.  if(response.getStatusLine().getStatusCode() == 200){  
  19.   return true;  
  20.  }  
  21.  return false;  
  22. }  

 


三、通過HTTP協議上傳文件數據
分析上傳文件的HTTP協議
Content-Type: multipart/form-data; boundary=---------------------------7db1861b605fa
實體數據分隔線:用於分隔每一個請求參數
示例:
(1)定義部分:boundary=---------------------------7db1861b605fa
(2)實體數據部分:     -----------------------------7db1861b605fa(多出兩個--)
        -----------------------------7db1861b605fa--(最後的--表示實體數據部分結束)
服務器對上傳文件大小有限制,一般最大是2M(文件過大時不建議使用HTTP協議)。

[java] view plaincopy

  1. /** 
  2.  * 上傳文件 
  3.  */  
  4. public class FormFile {  
  5.  /* 上傳文件的數據 */  
  6.  private byte[] data;  
  7.  private InputStream inStream;  
  8.  private File file;  
  9.  /* 文件名稱 */  
  10.  private String filename;  
  11.  /* 請求參數名稱*/  
  12.  private String parameterName;  
  13.  /* 內容類型 */  
  14.  private String contentType = "application/octet-stream";  
  15.  //上傳小容量的文件建議使用此構造方法  
  16.  public FormFile(String filename, byte[] data, String parameterName, String contentType) {  
  17.   this.data = data;  
  18.   this.filename = filename;  
  19.   this.parameterName = parameterName;  
  20.   if(contentType != null)  
  21.    this.contentType = contentType;  
  22.  }  
  23.  //上傳大容量的文件建議使用此構造方法  
  24.  public FormFile(String filename, File file, String parameterName, String contentType) {  
  25.   this.filename = filename;  
  26.   this.parameterName = parameterName;  
  27.   this.file = file;  
  28.   try {  
  29.    this.inStream = new FileInputStream(file);  
  30.   } catch (FileNotFoundException e) {  
  31.    e.printStackTrace();  
  32.   }  
  33.   if(contentType != null)  
  34.    this.contentType = contentType;  
  35.  }  
  36.    
  37.  ..................................  
  38.    
  39. }  
  40. public static boolean post(String path, Map<String, String> params, FormFile[] files) throws Exception {  
  41.  // 定義客戶端socket對象  
  42.  Socket socket = null;  
  43.  // 定義字節輸入流對象  
  44.  OutputStream outStream = null;  
  45.  // 定義字符輸入流對象  
  46.  BufferedReader reader = null;  
  47.  try{  
  48.   // 定義數據分隔線  
  49.   final String BOUNDARY = "---------------------------7db1861b605fb";  
  50.   // 定義數據結束標誌  
  51.   final String ENDLINE = "--" + BOUNDARY + "--\r\n";  
  52.   
  53.   // 獲取實體數據內容及其總長度    
  54.   // 定義保存文本類型實體數據的字符串  
  55.   StringBuilder textEntity = new StringBuilder();  
  56.   int textDataLength = 0;  
  57.   // 1、獲取文本類型參數的實體數據及長度  
  58.   for (Map.Entry<String, String> entry : params.entrySet()) {  
  59.    textEntity.append("--");  
  60.    textEntity.append(BOUNDARY);  
  61.    textEntity.append("\r\n");  
  62.    textEntity.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");  
  63.    textEntity.append(entry.getValue());  
  64.    textEntity.append("\r\n");  
  65.   }  
  66.   byte [] textData = textEntity.toString().getBytes(enc);  
  67.   textDataLength = textData.length;  
  68.      
  69.   int fileDataLength = 0;  
  70.   // 定義保存文件類型實體數據的字符串  
  71.   StringBuilder fileEntity = new StringBuilder();  
  72.   byte [] fileData = null;  
  73.   // 2、獲取文件類型參數的實體數據及長度  
  74.   for (FormFile uploadFile : files) {  
  75.    fileEntity.append("--");  
  76.    fileEntity.append(BOUNDARY);  
  77.    fileEntity.append("\r\n");  
  78.    fileEntity.append("Content-Disposition: form-data;name=\""  
  79.      + uploadFile.getParameterName() + "\";filename=\""  
  80.      + uploadFile.getFilename() + "\"\r\n");  
  81.    fileEntity.append("Content-Type: " + uploadFile.getContentType() + "\r\n\r\n");  
  82.    fileData =  fileEntity.toString().getBytes(enc);  
  83.    fileDataLength += fileData.length;  
  84.    fileDataLength += "\r\n".getBytes(enc).length;  
  85.    if (uploadFile.getInStream() != null) {  
  86.     fileDataLength += uploadFile.getFile().length();  
  87.    } else {  
  88.     fileDataLength += uploadFile.getData().length;  
  89.    }  
  90.   }  
  91.   // 計算傳輸給服務器的實體數據總長度  
  92.   int dataLength = textDataLength + fileDataLength + ENDLINE.getBytes(enc).length;  
  93.   System.out.println("dataLength: " + dataLength);  
  94.     
  95.   // 編寫HTTP協議發送數據  
  96.   URL url = new URL(destpath);  
  97.   int port = url.getPort() == -1 ? 80 : url.getPort();  
  98.   System.out.println("url.getHost(): " + url.getHost());  
  99.   System.out.println("port: " + port);  
  100.   // 創建Socket連接  
  101.   socket = new Socket(InetAddress.getByName(url.getHost()), port);  
  102.   // 獲取輸入流對象  
  103.   outStream = socket.getOutputStream();  
  104.   /** 下面完成HTTP請求頭的發送  start **/  
  105.   StringBuilder requestHead = new StringBuilder();  
  106.   requestHead.append("POST " + url.getPath() + " HTTP/1.1\r\n");  
  107.   requestHead.append("Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, " +  
  108.     "application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, " +  
  109.     "application/vnd.ms-powerpoint, application/msword, */*\r\n");  
  110.   requestHead.append("Accept-Language: zh-CN\r\n");  
  111.   requestHead.append("Content-Type: multipart/form-data; boundary=" + BOUNDARY + "\r\n");  
  112.   requestHead.append("Host: " + url.getHost() + ":" + port + "\r\n");  
  113.   requestHead.append("Content-Length: " + dataLength + "\r\n");  
  114.   requestHead.append("Connection: Keep-Alive\r\n");  
  115.   // 根據HTTP協議在HTTP請求頭後面需要再寫一個回車換行  
  116.   requestHead.append("\r\n".getBytes(enc));  
  117.   outStream.write(requestHead.toString().getBytes(enc));  
  118.   /** 上面完成HTTP請求頭的發送  end **/  
  119.     
  120.   /** 下面發送實體數據  start **/  
  121.   // 發送所有文本類型的實體數據  
  122.   outStream.write(textData);  
  123.   // 發送所有文件類型的實體數據  
  124.   for (FormFile uploadFile : files) {  
  125.    // 發送文件類型實體數據  
  126.    outStream.write(fileData);  
  127.      
  128.    // 發送文件數據  
  129.    if (uploadFile.getInStream() != null) {  
  130.     byte[] buffer = new byte[1024];  
  131.     int len = 0;  
  132.     while ((len = uploadFile.getInStream().read(buffer)) != -1) {  
  133.      outStream.write(buffer, 0, len);  
  134.     }  
  135.     uploadFile.getInStream().close();  
  136.    } else {  
  137.     outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);  
  138.    }  
  139.    outStream.write("\r\n".getBytes(enc));  
  140.   }  
  141.   // 發送數據結束標誌,表示數據已經結束  
  142.   outStream.write(ENDLINE.getBytes(enc));  
  143.   outStream.flush();  
  144.   /** 上面發送實體數據  end **/  
  145.     
  146.   // 判斷數據發送是否成功  
  147.   reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));  
  148.   String content = reader.readLine();  
  149.   System.out.println("content: " + content);  
  150.   // 讀取web服務器返回的數據,判斷請求碼是否爲200,如果不是200,代表請求失敗  
  151.   if (content.indexOf("200") == -1) {  
  152.    return false;  
  153.   }  
  154.  } catch(Exception e){  
  155.   throw e;  
  156.  } finally {  
  157.   if(outStream != null){  
  158.    outStream.close();  
  159.   }  
  160.   if(reader != null){  
  161.    reader.close();  
  162.   }  
  163.   if(socket != null){  
  164.    socket.close();  
  165.   }  
  166.  }  
  167.  return true;  
  168. }  
  169. <!-- 訪問網絡的權限 -->  
  170. <uses-permission android:name="android.permission.INTERNET"/>  
  171. <!-- 在SDCard中創建與刪除文件權限 -->  
  172. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />  
  173. <!-- 往SDCard寫入數據權限 -->  
  174. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  


四、通過HTTP協議發送XML數據(作爲實體數據,不是作爲請求參數),並調用WebService
調用WebService時需要發送XML實體數據
1、發送XML數據給服務器

[java] view plaincopy

  1. public boolean sendXML(String path, String xml) throws Exception{  
  2.  byte [] data = xml.getBytes();  
  3.  URL url = new URL(path);  
  4.  HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  5.  conn.setRequestMethod("POST");  
  6.  conn.setConnectTimeout(5 * 1000);  
  7.  conn.setDoOutput(true);  
  8.  conn.setRequestProperty("Content-Type""text/xml; charset=UTF-8");  
  9.  conn.setRequestProperty("Content-Length", String.valueOf(data.length));  
  10.  OutputStream outputStream = conn.getOutputStream();  
  11.  outputStream.write(data);  
  12.  outputStream.flush();  
  13.  outputStream.close();  
  14.  if(conn.getResponseCode() == 200){  
  15.   return true;  
  16.  }  
  17.  return false;  
  18. }  

 

2、發送SOAP數據給服務器調用WebService,實現手機號歸屬地查詢
SOAP協議基於XML格式
http://www.webxml.com.cn/
http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx

SOAP 1.2 請求示例。所顯示的[]需替換爲實際值。

 

[java] view plaincopy

  1. POST /WebServices/MobileCodeWS.asmx HTTP/1.1  
  2. Host: webservice.webxml.com.cn  
  3. Content-Type: application/soap+xml; charset=utf-8  
  4. Content-Length: length  
  5.   
  6. <?xml version="1.0" encoding="utf-8"?>  
  7. <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">  
  8.   <soap12:Body>  
  9.     <getMobileCodeInfo xmlns="http://WebXml.com.cn/">  
  10.       <mobileCode>[string]</mobileCode>  
  11.       <userID>[string]</userID>  
  12.     </getMobileCodeInfo>  
  13.   </soap12:Body>  
  14. </soap12:Envelope>  

 

SOAP 1.2 響應示例。所顯示的[]需替換爲實際值。

 

[java] view plaincopy

  1. HTTP/1.1 200 OK  
  2. Content-Type: application/soap+xml; charset=utf-8  
  3. Content-Length: length  
  4.   
  5. <?xml version="1.0" encoding="utf-8"?>  
  6. <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">  
  7.   <soap12:Body>  
  8.     <getMobileCodeInfoResponse xmlns="http://WebXml.com.cn/">  
  9.       <getMobileCodeInfoResult>[string]</getMobileCodeInfoResult>  
  10.     </getMobileCodeInfoResponse>  
  11.   </soap12:Body>  
  12. </soap12:Envelope>  

 

 

[java] view plaincopy

  1. /** 
  2.  * 發送SOAP數據給服務器調用WebService,實現手機號歸屬地查詢 
  3.  * @param path 
  4.  * @param soapXML 
  5.  * @return 
  6.  * @throws Exception 
  7.  */  
  8. public String getMobileCodeInfo(String path, InputStream inStream, String mobileCode) throws Exception{  
  9.  String soapXML = readSoapXML(inStream, mobileCode);  
  10.  byte [] data = soapXML.getBytes();  
  11.  URL url = new URL(path);  
  12.  HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  13.  conn.setRequestMethod("POST");  
  14.  conn.setConnectTimeout(5 * 1000);  
  15.  conn.setDoOutput(true);  
  16.  conn.setRequestProperty("Content-Type""application/soap+xml; charset=utf-8");  
  17.  conn.setRequestProperty("Content-Length", String.valueOf(data.length));  
  18.  OutputStream outputStream = conn.getOutputStream();  
  19.  outputStream.write(data);  
  20.  outputStream.flush();  
  21.  outputStream.close();  
  22.  if(conn.getResponseCode() == 200){  
  23.   //byte [] responseData = StreamTools.readInputStream(conn.getInputStream());  
  24.   //String responseXML = new String(responseData);  
  25.   //return responseXML;  
  26.     
  27.   return parseResponseXML(conn.getInputStream());  
  28.  }  
  29.  return null;  
  30. }  
  31. private String parseResponseXML(InputStream inStream) throws Exception{  
  32.  XmlPullParser parser = Xml.newPullParser();  
  33.  parser.setInput(inStream, "UTF-8");  
  34.  int eventType = parser.getEventType();  
  35.  while(eventType != XmlPullParser.END_DOCUMENT){  
  36.   switch (eventType) {   
  37.   case XmlPullParser.START_TAG:  
  38.    String name = parser.getName();  
  39.    if("getMobileCodeInfoResult".equals(name)){  
  40.     return parser.nextText();  
  41.    }  
  42.    break;  
  43.   }  
  44.   eventType = parser.next();  
  45.  }  
  46.  return null;  
  47. }  
  48. /** 
  49.  * 讀取MobileCodeWS.xml(要符合SOAP協議),並且替換其中的佔位符 
  50.  * @param inStream 
  51.  * @param mobileCode 真實手機號碼 
  52.  * @return 
  53.  * @throws Exception 
  54.  */  
  55. public String readSoapXML(InputStream inStream, String mobileCode) throws Exception{  
  56.  byte [] data = StreamTools.readInputStream(inStream);  
  57.  String soapXML = new String(data);  
  58.  Map<String, String> params = new HashMap<String, String>();  
  59.  params.put("mobileCode", mobileCode);  
  60.  //替換掉MobileCodeWS.xml中佔位符處的相應內容  
  61.  return replace(soapXML, params);  
  62. }  
  63. private String replace(String soapXML, Map<String, String> params) throws Exception{  
  64.  String result = soapXML;  
  65.  if(params != null && !params.isEmpty()){  
  66.   for(Map.Entry<String, String> entry : params.entrySet()){  
  67.    String regex = "\\*"+ entry.getKey();  
  68.    Pattern pattern = Pattern.compile(regex);  
  69.    Matcher matcher = pattern.matcher(result);  
  70.    if(matcher.find()){  
  71.     result = matcher.replaceAll(entry.getValue());  
  72.    }  
  73.   }  
  74.  }  
  75.  return result;  
  76. }  

 

 


五、通過HTTP協議實現多線程斷點下載
使用多線程下載文件可以提高文件下載的速度,更快完成文件的下載。多線程下載文件之所以快,是因爲其搶佔的服務器資源多。假設服務器同時最多服務100個用戶,在服務器中一條線程對應一個用戶,100條線程在計算機中並非併發執行,而是由CPU劃分時間片輪流執行,如果A用戶使用了99條線程下載文件,那麼相當於佔用了99個用戶的資源,如果一秒內CPU分配給每條線程的平均執行時間是10ms,A用戶在服務器中一秒內就得到了990ms的執行時間,而其他用戶在一秒內只有10ms的執行時間。好比一個水龍頭,每秒出水量相等的情況下,放990毫秒的水肯定比放10毫秒的水要多。
1、多線程下載的實現過程:
①、首先得到下載文件的長度,然後設置本地文件的長度。

[java] view plaincopy

  1. //獲取下載文件的長度  
  2. int fileLength = HttpURLConnection.getContentLength();  
  3. //在本地硬盤創建和需下載文件長度相同的文件。  
  4. RandomAccessFile file = new RandomAccessFile("QQ2011.exe""rwd");  
  5. //設置本地文件的長度和下載文件長度相同  
  6. file.setLength(fileLength);  
  7. file.close();  

 

②、根據文件長度和線程數計算每條線程下載的數據長度和下載位置。
a:每條線程下載的數據長度: 文件長度 % 線程數 == 0 ? 文件長度 / 線程數 : 文件長度 / 線程數 + 1
例如:文件的長度爲6M,線程數爲3,那麼每條線程下載的數據長度爲2M。
b: 每條線程從文件的什麼位置開始下載到什麼位置結束:
開始位置:線程id(從0開始) * 每條線程下載的數據長度
結束位置:(線程id + 1) * 每條線程下載的數據長度 - 1

③、使用HTTP的請求頭字段Range指定每條線程從文件的什麼位置開始下載,到什麼位置下載結束。
例如指定從文件的2M位置開始下載,下載到位置(4M-1byte)結束:

[java] view plaincopy

  1. HttpURLConnection.setRequestProperty("Range""bytes=2097152-4194303");  

 

④、保存文件。使用RandomAccessFile類指定每條線程從本地文件的什麼位置開始寫入數據。

[java] view plaincopy

  1. RandomAccessFile threadfile = new RandomAccessFile("QQ2011.exe""rwd");  
  2. //指定從文件的什麼位置開始寫入數據  
  3. threadfile.seek(2097152);  

 

⑤示例

 

[java] view plaincopy

  1. /** 
  2.  * 多線程下載 
  3.  * 從路徑中獲取文件名稱 
  4.  * @param path 下載路徑 
  5.  * @return 
  6.  */  
  7. public static String getFilename(String path){  
  8.  return path.substring(path.lastIndexOf('/') + 1);  
  9. }  
  10. /** 
  11.  * 多線程下載 
  12.  * 下載文件 
  13.  * @param path 下載路徑 
  14.  * @param threadNum 線程數 
  15.  */  
  16. public void download(String path, int threadNum) throws Exception{  
  17.  URL url = new URL(path);  
  18.  HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  19.  conn.setRequestMethod("GET");  
  20.  conn.setConnectTimeout(5 * 1000);  
  21.  //獲取要下載文件的長度  
  22.  int filelength = conn.getContentLength();  
  23.  //從路徑中獲取文件名稱  
  24.  String filename = getFilename(path);  
  25.  File saveFile = new File(filename);  
  26.  RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");  
  27.  //設置本地文件的長度和下載文件長度相同  
  28.  accessFile.setLength(filelength);  
  29.  accessFile.close();  
  30.  //計算每條線程下載的數據長度  
  31.  int block = filelength % threadNum == 0 ? filelength / threadNum : filelength / threadNum + 1;  
  32.  for(int threadid = 0 ; threadid < threadNum ; threadid++){  
  33.   new DownloadThread(url, saveFile, block, threadid).start();  
  34.  }  
  35. }  
  36.   
  37. /** 
  38.  * 多線程下載 
  39.  * 下載線程 
  40.  */  
  41. private final class DownloadThread extends Thread{  
  42.  private URL url;//下載文件的url  
  43.  private File saveFile;//本地文件  
  44.  private int block;//每條線程下載的數據長度  
  45.  private int threadid;//線程id  
  46.   
  47.  public DownloadThread(URL url, File saveFile, int block, int threadid) {  
  48.   this.url = url;  
  49.   this.saveFile = saveFile;  
  50.   this.block = block;  
  51.   this.threadid = threadid;  
  52.  }  
  53.   
  54.  @Override  
  55.  public void run() {  
  56.   //計算開始位置公式:線程id * 每條線程下載的數據長度  
  57.       //計算結束位置公式:(線程id + 1)* 每條線程下載的數據長度 - 1  
  58.   int startposition = threadid * block;  
  59.   int endposition = (threadid + 1 ) * block - 1;  
  60.   try {  
  61.    RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");  
  62.    //設置從什麼位置開始寫入數據  
  63.    accessFile.seek(startposition);  
  64.    HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  65.    conn.setRequestMethod("GET");  
  66.    conn.setConnectTimeout(5 * 1000);  
  67.    conn.setRequestProperty("Range""bytes=" + startposition + "-" + endposition);  
  68.    InputStream inStream = conn.getInputStream();  
  69.    byte[] buffer = new byte[1024];  
  70.    int len = 0;  
  71.    while( (len = inStream.read(buffer)) != -1 ){  
  72.     accessFile.write(buffer, 0, len);  
  73.    }  
  74.    inStream.close();  
  75.    accessFile.close();  
  76.    System.out.println("線程id:" + threadid + " 下載完成");  
  77.   } catch (Exception e) {  
  78.    e.printStackTrace();  
  79.   }  
  80.  }  
  81. }  

2、如何實現多線程斷點下載呢?
需要把每條線程下載數據的最後位置保存起來。

 

[java] view plaincopy

  1. main.xml文件:  
  2. <?xml version="1.0" encoding="utf-8"?>  
  3. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:orientation="vertical"  
  5.     android:layout_width="fill_parent"  
  6.     android:layout_height="fill_parent"  
  7.     >  
  8.     <TextView   
  9.      android:layout_width="fill_parent"  
  10.      android:layout_height="wrap_content"  
  11.      android:text="@string/downloadpath"  
  12.      />  
  13.      
  14.     <EditText   
  15.      android:layout_width="fill_parent"  
  16.      android:layout_height="wrap_content"  
  17.      android:text="http://dl_dir.qq.com/qqfile/qq/QQ2011/QQ2011Beta2.exe"  
  18.      android:id="@+id/downloadpath"  
  19.      />  
  20.    
  21.     <Button   
  22.      android:layout_width="wrap_content"  
  23.      android:layout_height="wrap_content"  
  24.      android:text="@string/download"  
  25.      android:id="@+id/download"  
  26.      />  
  27.     <!-- 進度條 -->  
  28.     <ProgressBar  
  29.      android:layout_width="fill_parent"  
  30.      android:layout_height="20px"  
  31.      style="?android:attr/progressBarStyleHorizontal"  
  32.      android:id="@+id/downloadbar"  
  33.      />  
  34.     <TextView   
  35.      android:layout_width="fill_parent"  
  36.      android:layout_height="wrap_content"  
  37.      android:gravity="center"//設置內容居中  
  38.      android:id="@+id/result"  
  39.      />   
  40. </LinearLayout>  

 

strings.xml文件:

[java] view plaincopy

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="hello">Hello World, DownloadActivity!</string>  
  4.     <string name="app_name">多線程文件下載器</string>  
  5.     <string name="downloadpath">下載路徑</string>  
  6.     <string name="download">下載</string>  
  7.     <string name="sdcarderror">SDCard不存在或者寫保護</string>  
  8.     <string name="success">下載完成</string>  
  9.     <string name="failure">下載失敗</string>  
  10. </resources>  

 

DownloadActivity:

[java] view plaincopy

  1. public class DownloadActivity extends Activity {  
  2.     private EditText downloadpathText;  
  3.     private TextView resultView;  
  4.     private ProgressBar progressBar;  
  5.     // 當Handler被創建時會關聯到創建它的當前線程(UI線程)的消息隊列中,Handler類用於往消息隊列發送消息,  
  6.     // 消息隊列中的消息由當前線程內部進行處理。  
  7.     private Handler handler = new Handler(){  
  8.   public void handleMessage(Message msg) {     
  9.    switch (msg.what) {  
  10.    case 1:   
  11.     //runOnUiThread();    
  12.     progressBar.setProgress(msg.getData().getInt("size"));  
  13.     float num = (float)progressBar.getProgress() / (float)progressBar.getMax();  
  14.     int result = (int)(num * 100);  
  15.     resultView.setText(result + "%");  
  16.     if(progressBar.getProgress() == progressBar.getMax()){  
  17.      Toast.makeText(DownloadActivity.this, R.string.success, 1).show();  
  18.     }  
  19.     break;  
  20.    case -1:  
  21.     Toast.makeText(DownloadActivity.this, R.string.failure, 1).show();  
  22.     break;  
  23.    }  
  24.   }  
  25.     };  
  26.      
  27.     @Override  
  28.     public void onCreate(Bundle savedInstanceState) {  
  29.         super.onCreate(savedInstanceState);  
  30.         setContentView(R.layout.main);  
  31.          
  32.         downloadpathText = (EditText) this.findViewById(R.id.downloadpath);  
  33.         progressBar = (ProgressBar) this.findViewById(R.id.downloadbar);  
  34.         resultView = (TextView) this.findViewById(R.id.result);  
  35.         Button downloadButton = (Button) this.findViewById(R.id.download);  
  36.         downloadButton.setOnClickListener(new View.OnClickListener() {  
  37.   public void onClick(View v) {  
  38.    String downloadpath = downloadpathText.getText().toString();  
  39.    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  
  40.     download(downloadpath, Environment.getExternalStorageDirectory());  
  41.    }else{  
  42.     Toast.makeText(DownloadActivity.this, R.string.sdcarderror, 1).show();  
  43.    }  
  44.      
  45.   }  
  46.  });  
  47.     }  
  48.     // 該方法可能會執行幾秒鐘(下載2、3M的文件),也有可能執行幾十分鐘或者更長時間(下載幾百M的文件),因此會阻塞當前實例所在的主線程(UI線程)。  
  49.     /* 當應用程序啓動時,系統會爲應用程序創建一個主線程(main)或者叫UI線程,它負責分發事件到不同的組件,包括繪畫事件,完成你的應用程序與Android UI組件交互。例如,當您觸摸屏幕上的一個按鈕時,UI線程會把觸摸事件分發到組件上,更改狀態並加入事件隊列,UI線程會分發請求和通知到各個組件,完成相應的動作。單線程模型的性能是非常差的,除非你的應用程序相當的簡單,特別是當所有的操作都在主線程中執行,比如訪問網絡或數據庫之類的耗時操作將會導致用戶界面鎖定,所有的事件將不能分發,應用程序就像死了一樣,更嚴重的是當超過5秒時,系統就會彈出(ANR)“應用程序無響應”的對話框。如果你想看看什麼效果,可以寫一個簡單的應用程序,在一個Button的OnClickListener中寫上Thread.sleep(2000),運行程序你就會看到在應用程序回到正常狀態前按鈕會保持按下狀態2秒,當這種情況發生時,您就會感覺到應用程序反映相當的慢。總之,我們需要保證主線程(UI線程)不被鎖住,如果有耗時的操作,我們需要把它放到一個【單獨的後臺線程】中執行。對於顯示控件的界面更新只是由UI線程負責,如果是在非UI線程更新控件的屬性值,更新後的顯示界面不會反映到屏幕上。怎麼辦? */  
  50.     private void download(final String downloadpath, final File savedir) {  
  51.      new Thread(new Runnable() {  
  52.   public void run() {  
  53.    // 在Android中不建議開啓太多下載線程,因此在此處開啓3個下載線程  
  54.    FileDownloader loader = new FileDownloader(DownloadActivity.this, downloadpath, savedir, 3);  
  55.    // 設置進度條的最大刻度爲文件的長度  
  56.    progressBar.setMax(loader.getFileSize());  
  57.    try {  
  58.     loader.download(new DownloadProgressListener() {  
  59.      // 實時獲知文件已經下載的數據長度        
  60.      public void onDownloadSize(int size) {  
  61.       // 讓進度條的當前刻度等於已下載文件的數據長度  
  62.       //progressBar.setProgress(loader.getFileSize());  
  63.       //float num = (float)progressBar.getProgress() / (float)progressBar.getMax();  
  64.       //int result = (int)(num * 100);  
  65.       //resultView.setText(result + "%");  
  66.       Message msg = new Message();  
  67.       // 定義消息ID  
  68.       msg.what = 1;  
  69.       msg.getData().putInt("size", size);  
  70.       // 發送消息(發送到UI線程綁定的消息隊列)  
  71.       handler.sendMessage(msg);  
  72.      }  
  73.     });  
  74.    } catch (Exception e) {  
  75.     //Message msg = new Message();  
  76.     //msg.what = -1;  
  77.     //handler.sendMessage(msg);  
  78.     handler.obtainMessage(-1).sendToTarget();  
  79.    }  
  80.   }  
  81.  }).start();  
  82.     }  
  83. }  

 


六、通過TCP/IP(Socket)協議實現斷點續傳上傳文件(實現多用戶併發訪問)
斷點續傳
大容量文件
多用戶、併發訪問
1、服務器在指定端口監聽。
2、客戶端連接至服務器的指定端口。
3、客戶端發送協議給服務器(第一次):
Content-length=69042560;filename=***.exe;sourceid=
4、服務器判斷sourceid是否存在,然後判斷是否存在該文件的上傳記錄,如果不存在sourceid,則生成sourceid,發送給客戶端。
服務器發送協議給客戶端(第一次)
sourceid=244242411345677;position=0
5、在客戶端將sourceid與filename進行關聯綁定,然後從position指定的位置開始上傳。
6、如果不是第一次上傳,獲取上傳文件的絕對路徑,在客戶端上傳記錄中尋找對應的sourceid,然後發送協議給服務器。
Content-length=897869;filename=***.exe;sourceid=244242411345677
7、服務器根據sourceid,在上傳的斷點記錄中查找是否存在該記錄,如果存在,獲取最後上傳的位置,發送協議給客戶端。
sourceid=244242411345677;position=223
8、客戶端從position位置繼續上傳文件。

ExecutorService:線程池
PushbackInputStream擁有一個PushBack緩衝區,通過PushbackInputStream讀出數據後,只要PushBack緩衝區沒有滿,就可以使用unread()將數據推回流的前端。
簡單地說,該流可以把剛讀過的字節退回到輸入流中,以便重新再讀一遍。


main.xml:

[java] view plaincopy

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:orientation="vertical"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     >  
  6.     <TextView   
  7.      android:layout_width="fill_parent"  
  8.      android:layout_height="wrap_content"  
  9.      android:text="@string/filename"  
  10.      />     
  11.     <EditText   
  12.      android:layout_width="fill_parent"  
  13.      android:layout_height="wrap_content"  
  14.      android:text="SPlayer.exe"  
  15.      android:id="@+id/filename"  
  16.      />      
  17.     <Button   
  18.      android:layout_width="wrap_content"  
  19.      android:layout_height="wrap_content"  
  20.      android:text="@string/upload"  
  21.      android:id="@+id/upload"  
  22.      />  
  23.     <ProgressBar  
  24.      android:layout_width="fill_parent"  
  25.      android:layout_height="20px"  
  26.      style="?android:attr/progressBarStyleHorizontal"  
  27.      android:id="@+id/uploadbar"  
  28.      />  
  29.     <TextView   
  30.      android:layout_width="fill_parent"  
  31.      android:layout_height="wrap_content"  
  32.      android:gravity="center"  
  33.      android:id="@+id/result"  
  34.      />  
  35. </LinearLayout>  

 

strings.xml:

[java] view plaincopy

  1. <resources>  
  2.     <string name="hello">Hello World, UploadActivity!</string>  
  3.     <string name="app_name">大視頻文件斷點上傳</string>  
  4.     <string name="filename">文件名稱</string>  
  5.     <string name="upload">上傳</string>  
  6.     <string name="sdcarderror">SDCard不存在或者寫保護</string>  
  7.     <string name="success">上傳完成</string>  
  8.     <string name="failure">上傳失敗</string>  
  9.     <string name="fileNotExsit">文件不存在</string>  
  10. </resources> 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章