標籤:android style blog http io color ar os sp
設定逾時:
URL url1 = new URL(url); HttpURLConnection conn = (HttpURLConnection) url1.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(3000); //3s conn.setReadTimeout(3000); //3s conn.setDoOutput(true);
本來以為設定了逾時程式就會自動返回,不會有異常了,經過反覆調試,的確會拋出SocketTimeoutException 異常
在
out = conn.getOutputStream(); //只是一個承載post內容的東西,這裡並沒有發送,必須在getInputStream之前
這一句會卡主,然後就異常了,所以我們要判斷是否逾時,則捕捉SocketTimeoutException異常就可以
整個post要求方法代碼如下:
public static String sendPostRequest(String url, Map<String, String> params, Map<String, String> headers) throws Exception { StringBuilder buf = new StringBuilder(); Set<Entry<String, String>> entrys = null; String result=null; // 如果存在參數,則放在HTTP請求體,形如name=aaa&age=10// if (params != null && !params.isEmpty()) {// entrys = params.entrySet();// for (Map.Entry<String, String> entry : entrys) {// buf.append(entry.getKey()).append("=")// .append(URLEncoder.encode(entry.getValue(), "UTF-8"))// .append("&");// }// buf.deleteCharAt(buf.length() - 1);// } //將參數化為xml 格式傳輸,格式為:<xml><datatype><![CDATA[3]]></datatype></xml> if (params != null && !params.isEmpty()) { entrys = params.entrySet(); buf.append("<xml>"); for (Map.Entry<String, String> entry : entrys) { buf.append("<").append(entry.getKey()).append("><![CDATA[") .append(URLEncoder.encode(entry.getValue(), "UTF-8")) .append("]]></").append(entry.getKey()).append(">"); } buf.append("</xml>"); } URL url1 = new URL(url); HttpURLConnection conn = (HttpURLConnection) url1.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(3000); conn.setReadTimeout(3000); conn.setDoOutput(true); OutputStream out=null; try { out = conn.getOutputStream(); //只是一個承載post內容的東西,這裡並沒有發送,必須在getInputStream之前 out.write(buf.toString().getBytes("UTF-8")); out.flush(); if (headers != null && !headers.isEmpty()) { entrys = headers.entrySet(); for (Map.Entry<String, String> entry : entrys) { conn.setRequestProperty(entry.getKey(), entry.getValue()); } } //conn.getResponseCode(); // 為了發送成功 if (conn.getResponseCode() == 200) { // 擷取響應的輸入資料流對象 InputStream is = conn.getInputStream(); //真正的發送請求 // 建立位元組輸出資料流對象 ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 定義讀取的長度 int len = 0; // 定義緩衝區 byte buffer[] = new byte[1024]; // 按照緩衝區的大小,迴圈讀取 while ((len = is.read(buffer)) != -1) { // 根據讀取的長度寫入到os對象中 baos.write(buffer, 0, len); } // 釋放資源 is.close(); baos.close(); // 返回字串 result = new String(baos.toByteArray()); } else { result = conn.getResponseCode()+""; } } catch (SocketTimeoutException ex) { result = "-3"; } return result; }
android 中設定HttpURLConnection 逾時並判斷是否逾時