Android心得8--Internet
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"/>
?
轉載于:https://www.cnblogs.com/yangkai-cn/archive/2012/07/09/4017123.html
總結
以上是生活随笔為你收集整理的Android心得8--Internet的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Hamcrest 精萃
- 下一篇: 淡定啊,学习啊