android 中設定HttpURLConnection 逾時並判斷是否逾時

來源:互聯網
上載者:User

標籤: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 逾時並判斷是否逾時

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.