1.從Internet擷取資料
利用HttpURLConnection對象,我們可以從網路中擷取網頁資料.
URLurl = new URL("http://www.sohu.com");
HttpURLConnectionconn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5*1000);//設定連線逾時
conn.setRequestMethod(“GET”);//以get方式發起請求
if(conn.getResponseCode() != 200) throw new RuntimeException("請求url失敗");
InputStreamis = conn.getInputStream();//得到網路返回的輸入資料流
Stringresult = readData(is, "GBK");
conn.disconnect();
//第一個參數為輸入資料流,第二個參數為字元集編碼
publicstatic String readData(InputStream inSream, String charsetName) throwsException{
ByteArrayOutputStream outStream = newByteArrayOutputStream();
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);
}
利用HttpURLConnection對象,我們可以從網路中擷取檔案資料.
URLurl = new URL("http://photocdn.sohu.com/20100125/Img269812337.jpg");
HttpURLConnectionconn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5*1000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() != 200) throw new RuntimeException("請求url失敗");
InputStreamis = conn.getInputStream();
readAsFile(is,"Img269812337.jpg");
publicstatic 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();
}
2. 多線程下載
使用多線程下載檔案可以更快完成檔案的下載,多線程下載檔案之所以快,是因為其搶佔的伺服器資源多。如:假設伺服器同時最多服務100個使用者,在伺服器中一條線程對應一個使用者,100條線程在電腦中並非並發執行,而是由CPU劃分時間片輪流執行,如果A應用使用了99條線程下載檔案,那麼相當於佔用了99個使用者的資源,假設一秒內CPU分配給每條線程的平均執行時間是10ms,A應用在伺服器中一秒內就得到了990ms的執行時間,而其他應用在一秒內只有10ms的執行時間。就如同一個水龍頭,每秒出水量相等的情況下,放990毫秒的水
肯定比放10毫秒的水要多。
多線程下載的實現過程:
1>首先得到下載檔案的長度,然後設定本地檔案的長度。
HttpURLConnection.getContentLength();
RandomAccessFilefile = new RandomAccessFile("QQWubiSetup.exe","rw");
file.setLength(filesize);//設定本地檔案的長度
2>根據檔案長度和線程數計算每條線程下載的資料長度和下載位置。如:檔案的長度為6M,線程數為3,那麼,每條線程下載的資料長度為2M,每條線程開始下載的位置如上圖所示。
3>使用Http的Range頭欄位指定每條線程從檔案的什麼位置開始下載,如:指定從檔案的2M位置開始下載檔案,代碼如下:
HttpURLConnection.setRequestProperty("Range","bytes=2097152-");
4>儲存檔案,使用RandomAccessFile類指定每條線程從本地檔案的什麼位置開始寫入資料。
RandomAccessFilethreadfile = new RandomAccessFile("QQWubiSetup.exe ","rw");
threadfile.seek(2097152);//從檔案的什麼位置開始寫入資料
3.向Internet發送請求參數
利用HttpURLConnection對象,我們可以向網路發送請求參數.
StringrequestUrl = "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();
URLrealUrl = new URL(requestUrl);
HttpURLConnectionconn = (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");
DataOutputStreamoutStream = 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);
}
4.向Internet發送xml資料
利用HttpURLConnection對象,我們可以向網路發送xml資料.
StringBuilderxml = new StringBuilder();
xml.append("<?xmlversion=\"1.0\" encoding=\"utf-8\" ?>");
xml.append("<M1V=10000>");
xml.append("<UI=1 D=\"N73\">中國</U>");
xml.append("</M1>");
byte[]xmlbyte = xml.toString().getBytes("UTF-8");
URLurl = newURL("http://localhost:8080/itcast/contanctmanage.do?method=readxml");
HttpURLConnectionconn = (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");
DataOutputStreamoutStream = new DataOutputStream(conn.getOutputStream());
outStream.write(xmlbyte);//發送xml資料
outStream.flush();
if(conn.getResponseCode() != 200) throw new RuntimeException("請求url失敗");
InputStreamis = conn.getInputStream();//擷取返回資料
Stringresult = readAsString(is, "UTF-8");
outStream.close();
5.<!-- 訪問internet許可權 -->
<uses-permission
android:name="android.permission.INTERNET"/>