【问题标题】:Java GET request returns response twiceJava GET 请求返回响应两次
【发布时间】:2016-03-23 18:05:04
【问题描述】:

我正在尝试编写一个可以将响应保存到文件的 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();
}

但是,它似乎总是返回两次响应。我在这里缺少一些逻辑吗?它返回整个响应,然后再次返回整个响应。

【问题讨论】:

    标签: java url get


    【解决方案1】:

    由于我们不知道 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()) 以验证代码在此之前是否有效。

    【讨论】:

      【解决方案2】:

      试试这个,看看它是否有效

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-17
        • 1970-01-01
        • 1970-01-01
        • 2016-11-28
        • 1970-01-01
        相关资源
        最近更新 更多