• android 中设置HttpURLConnection 超时并判断是否超时


    设置超时:

    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;
        }
  • 相关阅读:
    分答是什么?
    判定表
    总结
    周结
    第五周周结
    周结
    一周总结(18周)
    一周总结(17周)
    一周总结(16周)
    一周总结(15周)
  • 原文地址:https://www.cnblogs.com/feijian/p/4083752.html
Copyright © 2020-2023  润新知