我正在尝试编写一个可以保存对文件的响应的GET处理程序。
public String get(String[] args) throws IOException {
URL url = new URL(args[1]);
BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream()));
String output = "";
String line = input.readLine();
while(line != null){
output += line + "\n";
line = input.readLine();
}
saveGetToFile(output);
return "Response saved to: " + path.toString();
}
然而,它似乎总是两次返回响应。我在这里缺少一些逻辑吗?它返回整个响应,然后再返回整个响应。
答案 0 :(得分:0)
由于我们不知道saveGetToFile(String)
做了什么,以及path
变量包含什么,我们无法知道这些行中会发生什么。但是你的代码在那时很好,除了你忘了关闭流。
public String get() throws IOException {
URL url = new URL("http://httpbin.org/get");
StringBuilder builder = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line).append("\n");
}
} finally {
if (reader!=null) {
reader.close();
}
}
saveGetToFile(builder.toString()); //Does this method modify the value of your variable 'path'?
return "Response saved to: " + path.toString(); //Where do you write to path?
}
如果需要,请设置System.out.println(builder.toString())
以验证代码在此之前有效。
答案 1 :(得分:-1)
试一下,看看它是否有效
public String get(String[] args) throws IOException {
URL url = new URL(args[1]);
BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream()));
String output = "";
String line;
while((line=input.readLine())!= null){
output += line + "\n";
}
saveGetToFile(output);
return "Response saved to: " + path.toString();
}