我的节目停在了以下一行:
InputStream is = conn.getInputStream();
控制台上没有弹出错误消息或显示任何输出。 我在Red Hat Enterprise Linux Server 7.4版上运行Eclipse Oxygen 4.7.0。
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);
}
}
我注意到问了类似的问题InputStream is = httpURLConnection.getInputStream(); stop working 但这是针对Android而没有给出解决方案。
有没有人对此有所了解?不要犹豫,在我的代码中指出其他任何错误。
非常感谢!
答案 0 :(得分:0)
您的服务器没有响应。
使用conn.setReadTimeout(5000)
(比如说)设置读取超时是明智的。根据需要调整超时。
答案 1 :(得分:0)
检查响应代码
int response = connection.getResponseCode();
如果您收到301,则表示您的资源已重定向。尝试将URI从http更改为https。
对我来说有帮助。