Why HttpURLConnection.getInputStream stop working

2019-08-16 08:19发布

问题:

My program below stopped at the line:

InputStream is = conn.getInputStream();

Neither error message popped up nor any output displayed on the console. I am running Eclipse Oxygen 4.7.0 on Red Hat Enterprise Linux Server release 7.4.

 public static void solveInstance(String instanceName){
            // solve a problem instance
            try{
                String query_url = "http://localhost:8807/scheduler";

                // read Request to a JSON Object
                JSONParser parser = new JSONParser();
                JSONObject request = (JSONObject) parser.parse(new FileReader(instanceName));

                // open connection
                URL url = new URL(query_url);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");

                // POST Request
                OutputStream os = conn.getOutputStream();
                OutputStreamWriter osw =  new OutputStreamWriter(os, "UTF-8");
                osw.write(request.toString());
                osw.close();

                // Get Response
                InputStream is = conn.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader in = new BufferedReader(isr);

                String inputLine;
                StringBuffer response = new StringBuffer();
                while(( inputLine = in.readLine()) != null )
                {
                    response.append(inputLine);
                }
                in.close();

                // Write response to a file
                JSONObject jsonObj = (JSONObject) parser.parse(response.toString());
                String responseFile = /path_to_result/result.json;

                FileWriter fileWriter = new FileWriter(responseFile);
                fileWriter.write(jsonObj.toString());
                fileWriter.flush();
                fileWriter.close();

                System.out.println("Solved" + instanceName);
            }
            catch(Exception e) {
                System.out.println(e);
            }
        }

I noticed that the similar question is asked InputStream is = httpURLConnection.getInputStream(); stop working but it was for Android and no solution was given there.

Does anyone have some idea on that? Do not hesitate to point out anything else wrong in my code.

Thanks a lot!

回答1:

Your server isn't responding.

It would be wise to set a read timeout, with conn.setReadTimeout(5000) (say). Adjust the timeout as necessary.



标签: java http