如何在Java中重复发布和获取Http Service的响应?

时间:2018-03-23 02:10:57

标签: java http

我正在尝试重复访问Http服务" scheduler"。在每次访问中,我想向服务发布JSON请求并从服务获取JSON响应。

然而,HttpURLConnection.getInputStream()拒绝工作,即:

第一次致电

solveInstance(instanceName);

工作正常,但第二次电话被停留在

 InputStream is = conn.getInputStream();

"卡住"我的意思是该程序既没有错误信息也没有任何输出。我不确定它究竟是什么以及幕后发生了什么:(

这是代码。

public static void solveInstanceSet(String instanceSetName) {
        // run each instance in an Instance Set         
        try {
            // get the instanceSet File
            File instanceSet = new File(instanceSetName);
            Scanner scanner = new Scanner(instanceSet);

            // solve each instance in the file
            while(scanner.hasNext()) {
                String instanceName = scanner.nextLine();
                solveInstance(instanceName);
            }
        } catch(IOException e) {
            System.out.println("Exception: Cannot read the File contains the Instances to run!");
        }
    }

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();
        os.close();

        // Get Response: a schedule
        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();
        is.close();

        // write Response to a file
        JSONObject jsonObj = (JSONObject) parser.parse(response.toString());
        String responseFile = 
                "C:\\Path_To\\Result";

        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);
    }
}

我的代码中遗漏了什么?

注意: 我提出了一个相关问题Why HttpURLConnection.getInputStream stop working in Java。在那里,问题是只有一次调用函数。另请阅读我的评论以获取更多信息。

0 个答案:

没有答案