关于HttpURLConnection连接超时的问题

利物浦的红 发布于 2016/11/20 16:50
阅读 704
收藏 0
public String ottSendHttpReuqest(String serviceURL,String myCookie) throws Exception {
        try {
            URL url = new URL(serviceURL);
            HttpURLConnection urlConnection = (HttpURLConnection) url
                    .openConnection();
            urlConnection.setRequestMethod("GET");// 设置请求的方式
            urlConnection.setReadTimeout(5000);// 设置超时的时间
            urlConnection.setConnectTimeout(5000);// 设置链接超时的时间
            urlConnection.setRequestProperty("Cookie", myCookie);
            urlConnection.setRequestProperty("Content-type", "text/html");
            urlConnection.setRequestProperty("Accept-Charset", "utf-8");
            urlConnection.setRequestProperty("contentType", "utf-8");
            // 获取响应的状态码 404 200 505 302
            ottBoLogger.info("bo", "urlConnection.getResponseCode():------" + urlConnection.getResponseCode());
            if (urlConnection.getResponseCode() == 200) {
                // 获取响应的输入流对象
                InputStream is = urlConnection.getInputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(is, "GBK"));
                StringBuffer buffer = new StringBuffer();
                String line ="";
                while ((line = in.readLine())!=null){
                    buffer.append(line);
                }
                String result = buffer.toString();
 
                ottBoLogger.info("result", "result-------------" + result);
 
                // 释放资源
                is.close();
                in.close();
 
                return result;
            } else {
                System.out.println("------------------链接失败-----------------");
                return "requestError";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "requestError";
        }

    }


为什么执行到getResponseCode()这个方法的时候就抛出连接超时的异常?是不是需要执行connect()这个方法才算是连接上了?

加载中
0
游客
游客
format your code first
利物浦的红
求解答
返回顶部
顶部