在項目中使用了http的get和post方式鏈接,發送傳輸數據;服務器
public static String doGet(String httpUrl) { HttpURLConnection conn = null; InputStream is = null; BufferedReader br = null; String result = null; try { //建立遠程url連接 URL url = new URL(httpUrl); //經過遠程URL鏈接對象打開一個鏈接 conn = (HttpURLConnection) url.openConnection(); //設置鏈接方式爲get conn.setRequestMethod("GET"); //設置鏈接主機服務器的超時時間 conn.setConnectTimeout(15000); //設置讀取遠程返回的數據時間 conn.setReadTimeout(60000); //發送請求 conn.connect(); //經過鏈接,獲取輸入流 if(conn.getResponseCode() == 200) { is = conn.getInputStream(); //封裝輸入流is,並指定字符集 br = new BufferedReader(new InputStreamReader(is,"UTF-8")); //存放數據 StringBuffer sbf = new StringBuffer(); String temp = null; while((temp = br.readLine()) != null) { sbf.append(temp); } result = sbf.toString(); } } catch (Exception e) { e.printStackTrace(); }finally { close(conn,is,null,br); } return result; } public static String doPost(String httpUrl,String param) { HttpURLConnection conn = null; InputStream is = null; OutputStream os = null; BufferedReader br = null; String result = null; try { //建立遠程url連接 URL url = new URL(httpUrl); //經過遠程URL鏈接對象打開一個鏈接 conn = (HttpURLConnection) url.openConnection(); //設置鏈接方式爲get conn.setRequestMethod("POST"); //設置鏈接主機服務器的超時時間 conn.setConnectTimeout(15000); //設置讀取遠程返回的數據時間 conn.setReadTimeout(60000); //默認設置爲false,當向遠程服務器傳輸/寫數據 conn.setDoInput(true); //默認設置爲true,當前向遠程服務器時,設置爲true,該參數無關緊要 conn.setDoOutput(true); //設置傳入參數的格式:請求參數應該是name1 = value1,name2 = value2的形式 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //經過鏈接對象獲取一個輸出流 os = conn.getOutputStream(); //經過輸出流對象將數據寫出去 os.write(param.getBytes("UTF-8")); //經過鏈接,獲取輸入流 if(conn.getResponseCode() == 200) { is = conn.getInputStream(); //封裝輸入流is,並指定字符集 br = new BufferedReader(new InputStreamReader(is,"UTF-8")); //存放數據 StringBuffer sbf = new StringBuffer(); String temp = null; while((temp = br.readLine()) != null) { sbf.append(temp); } result = sbf.toString(); } } catch (Exception e) { e.printStackTrace(); }finally { close(conn,is,null,br); } return result; }