網絡傳輸---HttpURLConnection
阿新 • • 發佈:2018-02-14
false 遠程 style ext conn nec stream null col
HttpURLConnection是java做網絡傳輸的一種,一般用於做數據的傳輸如xml數據傳輸
1.創建及配置:
1.1創建一個url對象,並指定url的地址
URL url = new URL(urlString);
1.2 對此地址所引用的遠程對象的連接
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
1.3 對此連接進行配置
//設置HttpURLConnection參數 httpUrlConnection.setRequestMethod("POST"); // 設置是否向httpUrlConnection輸出,因為這個是post請求,參數要放在 // http正文內,因此需要設為true, 默認情況下是false; httpUrlConnection.setDoOutput(true); // 設置是否從httpUrlConnection讀入,默認情況下是true; httpUrlConnection.setDoInput(true); //設置不使用緩存 httpUrlConnection.setUseCaches(false); //設置發送請求為utf-8 httpUrlConnection.setRequestProperty("Content-type", "text/html;charset=utf-8"); //設置網絡請求時間最多為5秒; httpUrlConnection.setConnectTimeout(5000); //讀取網頁請求結果時間為15秒 httpUrlConnection.setReadTimeout(25000);
1.4 這些配置完成之後才能開啟連接
//連接,從上述url.openConnection()至此的配置必須要在connect之前完成, httpUrlConnection.connect();
2.獲得對HttpURLConnection遠程對象連接的輸出
//輸出 OutputStream out = httpUrlConnection.getOutputStream(); //用到了緩存流,提高IO效率,由於數據為字符,用到字符轉字節的包裝流,並設置UTF-8編碼 BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(out,"utf-8")); bout.write("demo"); bout.flush(); bout.close();
3.獲得對HttpURLConnection遠程對象連接的輸入結果
//獲得返回結果 if (httpUrlConnection.getResponseCode() == httpUrlConnection.HTTP_OK) {//判斷狀態碼是否為200 InputStream in = httpUrlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader( in)); StringBuffer stringBuffer = new StringBuffer(); String str = ""; while ((str = reader.readLine()) != null) { stringBuffer.append(str+"\n"); } reader.close(); in.close(); return stringBuffer.toString(); }else{ return null; }
4.PS:用到HttpURLConnection對象時肯定存在相對應的url地址,此時需要服務器部署url資源,用服務器對指定的請求做處理
網絡傳輸---HttpURLConnection