从servlet调用URL的异常

时间:2015-05-04 13:24:26

标签: java http servlets

我试图从servlet调用一个URL(URL只包含json代码)但是我一直在getInputStream()上获得读取超时异常。

public class SimpleServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse esponse) throws IOException, ServletException  {

        BufferedReader reader = null;
        StringBuilder stringBuilder;
        InputStream in=null;
        String json=null;

        URL url = new URL("http://localhost:8080/SimpleWeb/users");
        try{
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-type", "application/json");
            conn.setReadTimeout(5000);
            conn.connect();    

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));

            stringBuilder = new StringBuilder();
            String line=null;
            while((line = reader.readLine()) != null){
                stringBuilder.append(line + "\n");
            }
            json = stringBuilder.toString();
            System.out.println(json);
        }catch(Exception e){        
            System.out.println(e);
        }finally{
            if(reader!=null)
                reader.close();
        }
    }
}

代码的工作原理是将http://localhost:8080/SimpleWeb/users替换为http://localhost:8080/SimpleWeb/users.txt(但仅在从普通的Java应用程序而不是servlet中调用时)

任何人都可以帮忙看看我可能做错了吗?

0 个答案:

没有答案