Android之旅十五 android中的網路操作,android之旅
android中的網路操作和java裡面沒有什麼區別,java裡面的很多網路操作方法都可以搬到android中去使用,主要幾個點:
1、post和get請求的區別,大家可以在網上查閱有關資料進行瞭解,get主要以向地址中拼接字串參數發送到伺服器,長度有限制,並且請求參數暴露在地址欄中,不怎麼安全;post則主要是將請求參數轉換為相應的http協議請求體發送到伺服器,相比get方式,參數的長度沒有限制,並且參數資訊不會暴露給使用者;
2、我們在java web裡面通過瀏覽器以post方式發送資料,瀏覽器幫我們轉換為相應的http協議,也就是說瀏覽器內部幫我們設定為相應的http請求體,然後發送到伺服器,使用者通過瀏覽器向伺服器發送資料-->瀏覽器轉換為http協議-->發送到伺服器,如果我們用android做用戶端用java代碼編寫post請求,需要設定其請求體,而get方式請求則只需要拼接相應的參數地址,使用者通過android用戶端向伺服器發送資料-->編碼設定為相應的http協議-->發送到伺服器;
3、android裡麵包含了apache的httpclient,相當與web裡面的瀏覽器,我們還可以利用其api進行相應的請求操作,相比與純java代碼,它裡面封裝了很多東西,我們只需要根據業務需求選擇相應的api即可;如果我們在swing中使用apache的httpclient,則需要匯入其相應的jar包
post請求:
java web:使用者通過瀏覽器向伺服器發送資料-->瀏覽器轉換為http協議-->發送到伺服器
java代碼:使用者通過android用戶端向伺服器發送資料-->編碼設定為相應的http協議-->發送到伺服器
httpclient:使用者通過android用戶端向伺服器發送資料(httpclient幫我們轉換為相應的http協議)-->發送到伺服器
代碼實現功能:裡面都有相應的注釋,我在我的工程裡面建立了一個專門處理Http上傳、下載的類:HttpUtil
1、從伺服器擷取位元據,圖片、視頻等:
/** * 從伺服器上擷取位元據,例片、視頻等 * @param serverUrl: 伺服器位址 * @param newFileName:擷取到本地後新檔案的地址+名稱 例如:C://test.png */public static void getByteFromServer(String serverUrl,String newFileName)throws Exception{URL url = new URL(serverUrl);HttpURLConnection conn = (HttpURLConnection)url.openConnection();conn.setRequestMethod("GET");//通過Get方式請求conn.setConnectTimeout(5 * 1000);//設定串連延遲,因為android系統記憶體有限,不能長時間去與伺服器建立串連InputStream inStream = conn.getInputStream();//通過輸入資料流擷取圖片資料byte[] data = readInputStream(inStream);//得到圖片的位元據File imageFile = new File(newFileName);FileOutputStream outStream = new FileOutputStream(imageFile);outStream.write(data);outStream.close();}
/** * 將輸入資料流轉換為位元組資料 * @param inStream * @return * @throws Exception */public static byte[] readInputStream(InputStream inStream) throws Exception{ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while( (len=inStream.read(buffer)) != -1 ){outStream.write(buffer, 0, len);}inStream.close();return outStream.toByteArray();}
2、從伺服器擷取文本資訊,例如文本、html、xml、json等資料資訊
/** * 從伺服器上擷取文本資訊,例如html、xml等資訊 * @param serverUrl * @return 文本字串 */public static String getTxtFromServer(String serverUrl)throws Exception{URL url = new URL(serverUrl);HttpURLConnection conn = (HttpURLConnection)url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(5 * 1000);InputStream inStream = conn.getInputStream();//通過輸入資料流擷取txt資料byte[] data = readInputStream(inStream);//得到txt的位元據String txt = new String(data);return txt;}
3、以get方式向伺服器發送資料資訊
/**Get請求方式即是通過將參數放到地址中發送到伺服器 * 向伺服器發送Get請求 * @param path:伺服器請求地址 * @param params:請求參數 * @param enc:編碼 * @return true:請求成功 false:請求失敗 * @throws Exception */public static boolean sendGetRequest(String path, Map<String, String> params, String enc) throws Exception{StringBuilder sb = new StringBuilder(path);//?username=jack&password=123456&age=23if(params!=null && !params.isEmpty()){sb.append('?');for(Map.Entry<String, String> entry : params.entrySet()){sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), enc)).append('&');}sb.deleteCharAt(sb.length()-1);}URL url = new URL(sb.toString());HttpURLConnection conn = (HttpURLConnection)url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(5 * 1000);if(conn.getResponseCode()==200){//請求成功,可以調用上面的getByteFromServer方法得到相應的伺服器資料//byte[] b=readInputStream(conn.getInputStream());return true;}return false;}
4、以post方式向伺服器發送資料資訊:
/**Post請求在瀏覽器中是轉換了相應的http協議進行 * 而轉換後的http協議中包含了例如Content-Type、Content-Length等資訊 * 所以通過android用戶端發送post請求需要將其設定為相應的http協議發送出去 * 向伺服器發送一個post表單請求 * @param path:伺服器位址 * @param params:請求參數 * @param enc:編碼 * @return true:請求成功 false:請求失敗 * @throws Exception */public static boolean sendPostRequest(String path, Map<String, String> params, String enc) throws Exception{//username=jack&password=123456&age=23StringBuilder sb = new StringBuilder();if(params!=null && !params.isEmpty()){for(Map.Entry<String, String> entry : params.entrySet()){sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), enc)).append('&');}sb.deleteCharAt(sb.length()-1);}byte[] entitydata = sb.toString().getBytes();//得到實體的位元據URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection)url.openConnection();conn.setRequestMethod("POST");conn.setConnectTimeout(5 * 1000);conn.setUseCaches(false);//不進行緩衝conn.setDoOutput(true);//如果通過post提交資料,必須設定允許對外輸出資料//設定http要求標頭,向伺服器發送post請求,Content-Type和Content-Length兩個參數必須要,其他可省略//設定發送內容類型,為表單資料conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//設定發送內容長度conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length));conn.setRequestProperty("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, */*");conn.setRequestProperty("Accept-Language", "zh-CN");conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");conn.setRequestProperty("Connection", "Keep-Alive");OutputStream outStream = conn.getOutputStream();outStream.write(entitydata);outStream.flush();outStream.close();if(conn.getResponseCode()==200){//請求成功,可以調用上面的getByteFromServer方法得到相應的伺服器資料//byte[] b=readInputStream(conn.getInputStream());return true;}return false;}
5、以post方式向伺服器發送xml資料資訊:
/** * 向伺服器發送xml資料 * @param path:伺服器位址 * @param xml:xml字串資訊 * @param enc:編碼 * @return true:請求成功 false:請求失敗 * @throws Exception */public static boolean sendPostXMLRequest(String path, String xml,String enc)throws Exception{byte[] data = xml.getBytes();URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection)url.openConnection();conn.setRequestMethod("POST");conn.setConnectTimeout(5 * 1000);conn.setDoOutput(true);//如果通過post提交資料,必須設定允許對外輸出資料//設定發送內容類型,為xml資料conn.setRequestProperty("Content-Type", "text/xml; charset="+enc);//設定發送內容長度conn.setRequestProperty("Content-Length", String.valueOf(data.length));OutputStream outStream = conn.getOutputStream();outStream.write(data);outStream.flush();outStream.close();if(conn.getResponseCode()==200){//byte[] b=readInputStream(conn.getInputStream());return true;}return false;}
6、通過HttpClient以get方式向伺服器發送資料:
/** * 通過httpClient發送get請求 * @param path:伺服器位址 * @param params:參數名稱 * @param enc:編碼 * @return true:請求成功 false:請求失敗 * @throws Exception */public static boolean sendGetRequestFromHttpClient(String path, Map<String, String> params,String enc)throws Exception{StringBuilder sb = new StringBuilder(path);//?username=jack&password=123456&age=23if(params!=null && !params.isEmpty()){sb.append('?');for(Map.Entry<String, String> entry : params.entrySet()){sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), enc)).append('&');}sb.deleteCharAt(sb.length()-1);}//相當與瀏覽器 HttpClient httpClient=new DefaultHttpClient();//得到一個HttpGet對象HttpGet get=new HttpGet(sb.toString());//發送一個Get請求HttpResponse response=httpClient.execute(get);if(response.getStatusLine().getStatusCode()==200){//String str=EntityUtils.toString(response.getEntity());即可得到伺服器資料資訊//InputStream inStream=httpEntity.getContent();即可得到伺服器輸入資料流return true;}return false;}
7、通過HttpClient以post方式向伺服器發送請求:
/** * 通過httpClient發送Post請求 * @param path:伺服器位址 * @param params:參數名稱 * @param enc:編碼 * @return true:請求成功 false:請求失敗 * @throws Exception */public static boolean sendPostRequestFromHttpClient(String path, Map<String, String> params,String enc)throws Exception{List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();if(params!=null && !params.isEmpty()){for(Map.Entry<String, String> entry : params.entrySet()){paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}}UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs, enc);//得到經過編碼過後的實體資料HttpPost post = new HttpPost(path); //formpost.setEntity(entitydata);DefaultHttpClient client = new DefaultHttpClient(); //瀏覽器HttpResponse response = client.execute(post);//執行請求if(response.getStatusLine().getStatusCode()==200){//String str=EntityUtils.toString(response.getEntity());即可得到伺服器資料資訊//InputStream inStream=httpEntity.getContent();即可得到伺服器輸入資料流return true;}return false;}
8、通過post發送上傳檔案資訊到伺服器,相當與web表單提交,表單中包含上傳檔案,其實根據瀏覽器在上傳表單的時候它底層轉換為相應的http協議,我們也可以模仿其編寫相應的請求體然後提交給伺服器即可,瞭解其原理了就很容易去理解了;
建立表單實體檔案:
public class FormFile {/* 上傳檔案的資料 */private byte[] data;private InputStream inStream;private File file;/* 檔案名稱 */private String filname;/* 請求參數名稱*/private String parameterName;/* 內容類型 */private String contentType = "application/octet-stream";public FormFile(String filname, byte[] data, String parameterName, String contentType) {this.data = data;this.filname = filname;this.parameterName = parameterName;if(contentType!=null) this.contentType = contentType;}public FormFile(String filname, File file, String parameterName, String contentType) {this.filname = filname;this.parameterName = parameterName;this.file = file;try {this.inStream = new FileInputStream(file);} catch (FileNotFoundException e) {e.printStackTrace();}if(contentType!=null) this.contentType = contentType;}public File getFile() {return file;}public InputStream getInStream() {return inStream;}public byte[] getData() {return data;}public String getFilname() {return filname;}public void setFilname(String filname) {this.filname = filname;}public String getParameterName() {return parameterName;}public void setParameterName(String parameterName) {this.parameterName = parameterName;}public String getContentType() {return contentType;}public void setContentType(String contentType) {this.contentType = contentType;}}
發送包含File請求:
/** * 向伺服器提交的資訊包含上傳檔案資訊 * 直接通過HTTP協議提交資料到伺服器,實現如下面表單提交功能: * <FORM METHOD=POST ACTION="http://192.168.0.200:8080/ssi/fileload/test.do" enctype="multipart/form-data"><INPUT TYPE="text" NAME="name"><INPUT TYPE="text" NAME="id"><input type="file" name="imagefile"/> <input type="file" name="zip"/> </FORM> * @param path 上傳路徑(註:避免使用localhost或127.0.0.1這樣的路徑測試,因為它會指向手機模擬器,你可以使用http://www.itcast.cn或http://192.168.1.10:8080這樣的路徑測試) * @param params 請求參數 key為參數名,value為參數值 * @param file 上傳檔案 */public static boolean sendPostRequest(String path, Map<String, String> params, FormFile[] files) throws Exception{ final String BOUNDARY = "---------------------------7da2137580612"; //資料分隔線 final String endline = "--" + BOUNDARY + "--\r\n";//資料結束標誌 int fileDataLength = 0; for(FormFile uploadFile : files){//得到檔案類型資料的總長度 StringBuilder fileExplain = new StringBuilder(); fileExplain.append("--"); fileExplain.append(BOUNDARY); fileExplain.append("\r\n"); fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n"); fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n"); fileExplain.append("\r\n"); fileDataLength += fileExplain.length(); if(uploadFile.getInStream()!=null){ fileDataLength += uploadFile.getFile().length(); }else{ fileDataLength += uploadFile.getData().length; } } StringBuilder textEntity = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) {//構造文本型別參數的實體資料 textEntity.append("--"); textEntity.append(BOUNDARY); textEntity.append("\r\n"); textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n"); textEntity.append(entry.getValue()); textEntity.append("\r\n"); } //計算傳輸給伺服器的實體資料總長度 int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length; URL url = new URL(path); int port = url.getPort()==-1 ? 80 : url.getPort(); Socket socket = new Socket(InetAddress.getByName(url.getHost()), port); OutputStream outStream = socket.getOutputStream(); //下面完成HTTP要求標頭的發送 String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n"; outStream.write(requestmethod.getBytes()); 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"; outStream.write(accept.getBytes()); String language = "Accept-Language: zh-CN\r\n"; outStream.write(language.getBytes()); String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n"; outStream.write(contenttype.getBytes()); String contentlength = "Content-Length: "+ dataLength + "\r\n"; outStream.write(contentlength.getBytes()); String alive = "Connection: Keep-Alive\r\n"; outStream.write(alive.getBytes()); String host = "Host: "+ url.getHost() +":"+ port +"\r\n"; outStream.write(host.getBytes()); //寫完HTTP要求標頭後根據HTTP協議再寫一個斷行符號換行 outStream.write("\r\n".getBytes()); //把所有文本類型的實體資料發送出來 outStream.write(textEntity.toString().getBytes()); //把所有檔案類型的實體資料發送出來 for(FormFile uploadFile : files){ StringBuilder fileEntity = new StringBuilder(); fileEntity.append("--"); fileEntity.append(BOUNDARY); fileEntity.append("\r\n"); fileEntity.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n"); fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n"); outStream.write(fileEntity.toString().getBytes()); if(uploadFile.getInStream()!=null){ byte[] buffer = new byte[1024]; int len = 0; while((len = uploadFile.getInStream().read(buffer, 0, 1024))!=-1){ outStream.write(buffer, 0, len); } uploadFile.getInStream().close(); }else{ outStream.write(uploadFile.getData(), 0, uploadFile.getData().length); } outStream.write("\r\n".getBytes()); } //下面發送資料結束標誌,表示資料已經結束 outStream.write(endline.getBytes()); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); if(reader.readLine().indexOf("200")==-1){//讀取web伺服器返回的資料,判斷請求碼是否為200,如果不是200,代表請求失敗 return false; } outStream.flush(); outStream.close(); reader.close(); socket.close(); return true;}
大家可以將代碼複製下來看看,掌握好了以後就直接可以拿來用咯!!
怎在Android中實現一個簡單串連網路的應用程式
注意:要執行這節課中描述的網路操作,你應用程式的manifest檔案中必須包含以下許可權:1 2<uses-permissionandroid:name="android.permission.INTERNET"/><uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>選擇一個HTTP用戶端 Choose an HTTP Client大多數網路連接的Android應用使用HTTP發送和接受資料,Android包括兩個HTTP用戶端:HttpURLConnection和Apache HttpClient,它們支援HTTPS,流上傳和下載,
可配置的逾時,IPv6以及串連池,在android系統版本為“薑餅”(android2.3)或者更高版本的應用程式中,推薦使用HttpURLConnection,