HttpURLConnection没有收到响应

时间:2018-07-13 06:37:12

标签: java

我有WebService在Thread循环中调用代码。我用不同的参数构建URL,并使用HttpURLConnection调用WS,如下所示:

public void run() {
    //establish connection to db in another class

    while(true) {
        //Get args value from another class

        for(String arg : args) {
            try {
                String invokeWS = "URL is built here with encoded args";

                URL obj = new URL(invokeWS);

                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                con.setRequestMethod("GET");
                con.setRequestProperty("User-Agent", USER_AGENT);
                int responseCode = con.getResponseCode();
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                }
                in.close();
                con.disconnect();

                System.out.println(response.toString());
            } catch (UnsupportedEncodingException e) {
                System.out.println("Unsupported Encoding Exception");
            } catch (MalformedURLException e) {
                System.out.println("Malformed URL Exception");
            } catch (IOException e) {
                System.out.println("IO Exception");
            }
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted Exception");
        }
    }
}

但是,如果在发送“ GET”之后并且在收到响应之前网络连接中断,则控制将永远不会返回到循环中的线程。我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

避免在可运行的循环。我遇到了同样的问题,我减少了循环。我直接加载了数据,然后在可运行任务的最后循环。