從Internet擷取資料
利用HttpURLConnection對象,我們可以從網路中擷取網頁資料.
URL url = new URL("http://www.sohu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5* 1000);//設定連線逾時
conn.setRequestMethod(“GET”);//以get方式發起請求
if (conn.getResponseCode() != 200) throw new RuntimeException("請求url失敗");
InputStream is = conn.getInputStream();//得到網路返回的輸入資料流
String result = readData(is, "GBK");
conn.disconnect();
//第一個參數為輸入資料流,第二個參數為字元集編碼
public static String readData(InputStream inSream, String charsetName) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while( (len = inSream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inSream.close();
return new String(data, charsetName);
}
<!-- 訪問internet許可權 --> <uses-permission android:name="android.permission.INTERNET"/>
利用HttpURLConnection對象,我們可以從網路中擷取檔案資料. URL url = new URL("http://photocdn.sohu.com/20100125/Img269812337.jpg"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5* 1000); conn.setRequestMethod("GET"); if (conn.getResponseCode() != 200) throw new RuntimeException("請求url失敗"); InputStream is = conn.getInputStream(); readAsFile(is, "Img269812337.jpg"); public static void readAsFile(InputStream inSream, File file) throws Exception{ FileOutputStream outStream = new FileOutputStream(file); byte[] buffer = new byte[1024]; int len = -1; while( (len = inSream.read(buffer)) != -1 ){ outStream.write(buffer, 0, len); } outStream.close(); inSream.close(); }
多線程下載
使用多線程下載檔案可以更快完成檔案的下載,多線程下載檔案之所以快,是因為其搶佔的伺服器資源多。如:假設伺服器同時最多服務100個使用者,在伺服器中一條線程對應一個使用者,100條線程在電腦中並非並發執行,而是由CPU劃分時間片輪流執行,如果A應用使用了99條線程下載檔案,那麼相當於佔用了99個使用者的資源,假設一秒內CPU分配給每條線程的平均執行時間是10ms,A應用在伺服器中一秒內就得到了990ms的執行時間,而其他應用在一秒內只有10ms的執行時間。就如同一個水龍頭,每秒出水量相等的情況下,放990毫秒的水 肯定比放10毫秒的水要多。 多線程下載的實現過程: 1>首先得到下載檔案的長度,然後設定本地檔案 的長度。 HttpURLConnection.getContentLength(); RandomAccessFile file = new RandomAccessFile("QQWubiSetup.exe","rw"); file.setLength(filesize);//設定本地檔案的長度 2>根據檔案長度和線程數計算每條線程下載的資料長度和下載位置。如:檔案的長度為6M,線程數為3,那麼,每條線程下載的資料長度為2M,每條線程開始下載的位置如上圖所示。 3>使用Http的Range頭欄位指定每條線程從檔案的什麼位置開始下載,如:指定從檔案的2M位置開始下載檔案,代碼如下: HttpURLConnection.setRequestProperty("Range", "bytes=2097152-"); 4>儲存檔案,使用RandomAccessFile類指定每條線程從本地檔案的什麼位置開始寫入資料。 RandomAccessFile threadfile = new RandomAccessFile("QQWubiSetup.exe ","rw"); threadfile.seek(2097152);//從檔案的什麼位置開始寫入資料
向Internet發送請求參數 利用HttpURLConnection對象,我們可以向網路發送請求參數. String requestUrl = "http://localhost:8080/itcast/contanctmanage.do"; Map<String, String> requestParams = new HashMap<String, String>(); requestParams.put("age", "12"); requestParams.put("name", "中國"); StringBuilder params = new StringBuilder(); for(Map.Entry<String, String> entry : requestParams.entrySet()){ params.append(entry.getKey()); params.append("="); params.append(URLEncoder.encode(entry.getValue(), "UTF-8")); params.append("&"); } if (params.length() > 0) params.deleteCharAt(params.length() - 1); byte[] data = params.toString().getBytes(); URL realUrl = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setDoOutput(true);//發送POST請求必須設定允許輸出 conn.setUseCaches(false);//不使用Cache conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive");//維持長串連 conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(data); outStream.flush(); if( conn.getResponseCode() == 200 ){ String result = readAsString(conn.getInputStream(), "UTF-8"); outStream.close(); System.out.println(result); } 向Internet發送xml資料 利用HttpURLConnection對象,我們可以向網路發送請求參數. String requestUrl = "http://localhost:8080/itcast/contanctmanage.do"; Map<String, String> requestParams = new HashMap<String, String>(); requestParams.put("age", "12"); requestParams.put("name", "中國"); StringBuilder params = new StringBuilder(); for(Map.Entry<String, String> entry : requestParams.entrySet()){ params.append(entry.getKey()); params.append("="); params.append(URLEncoder.encode(entry.getValue(), "UTF-8")); params.append("&"); } if (params.length() > 0) params.deleteCharAt(params.length() - 1); byte[] data = params.toString().getBytes(); URL realUrl = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setDoOutput(true);//發送POST請求必須設定允許輸出 conn.setUseCaches(false);//不使用Cache conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive");//維持長串連 conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(data); outStream.flush(); if( conn.getResponseCode() == 200 ){ String result = readAsString(conn.getInputStream(), "UTF-8"); outStream.close(); System.out.println(result); } 向Internet發送xml資料 利用HttpURLConnection對象,我們可以向網路發送xml資料. StringBuilder xml = new StringBuilder(); xml.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); xml.append("<M1 V=10000>"); xml.append("<U I=1 D=\"N73\">中國</U>"); xml.append("</M1>"); byte[] xmlbyte = xml.toString().getBytes("UTF-8"); URL url = new URL("http://localhost:8080/itcast/contanctmanage.do?method=readxml"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5* 1000); conn.setDoOutput(true);//允許輸出 conn.setUseCaches(false);//不使用Cache conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive");//維持長串連 conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Length", String.valueOf(xmlbyte.length)); conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(xmlbyte);//發送xml資料 outStream.flush(); if (conn.getResponseCode() != 200) throw new RuntimeException("請求url失敗"); InputStream is = conn.getInputStream();//擷取返回資料 String result = readAsString(is, "UTF-8"); outStream.close();
大小: 11.3 KB internet.rar (40.1 KB) 下載次數: 97 MulThreadDownload.rar (76.3 KB) 下載次數: 110 ResCat.rar (77.2 KB) 下載次數: 71 web.rar (2.4 MB) 下載次數: 139 查看圖片附件