Java,HttpUrlConnection。 getResponseCode() 的问题

标签 java http webserver

我尝试使用 HTTP 创建最简单的 Simplest WebServer 和 Client。 (请不要告诉我使用 Apache HTTPClient)。

客户端:尝试将一些文件放入服务器。

// **PUT**
if(REQUEST.toUpperCase().equals("PUT")) {

  File sourceFile = new File(fileName);

  if(!sourceFile.canRead()) {
      System.out.println("Have not access to this file...");
      return;
  }

  try {
      BufferedInputStream is = new BufferedInputStream(new FileInputStream(sourceFile));

      URL url = new URL("http://" + HOST+":"+PORT);
      System.setProperty("http.keepAlive", "true");
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setDoInput(true);
      connection.setDoOutput(true);

      connection.setRequestMethod("PUT");
      connection.setRequestProperty("Content-Type", "Application/octet-stream");
      connection.setRequestProperty("Content-Length",Long.toString(sourceFile.length()));
      connection.addRequestProperty("Content-disposition","attachment; filename="+fileName);

      BufferedOutputStream os = new BufferedOutputStream(connection.getOutputStream());

      byte[] buf = new byte[sizeArr];
      int r = 1;
      while((r = is.read(buf)) > 0) {
          os.write(buf, 0, r);
      }
      os.flush();
      os.close();

      System.out.println("Waiting for the response...");//this is written to console

      System.out.println(connection.getResponseCode());//HERE infinite waiting
      is.close();


  } catch (MalformedURLException ex) {
      ex.printStackTrace();
  } catch (IOException ex) {
      ex.printStackTrace();
  }
  }

在服务器上:如果 Request == PUT,则:

// **PUT**
if (header.toUpperCase().equals("PUT")) {
    System.setProperty("http.keepAlive", "true");
    String fileName = null;

    if((fileName = extract(request.toUpperCase(),"FILENAME=","\n")) == null) {
        fileName = "UnknownFile.out";
    }

    try {
    File sourceFile = new File(fileName);
    BufferedOutputStream osFile = new BufferedOutputStream 
        (new FileOutputStream(sourceFile));

    byte[] locbuf = new byte[sizeArr];
    int locr = 1;
    while((locr = is.read(locbuf)) > 0) {
        System.out.println("locr= "+locr);//this is written to console
        osFile.write(locbuf, 0, locr);
    }
    System.out.println("Ending to record the data to the file."); 
    //  this is NOT written to console
    osFile.flush();
    osFile.close();
    }
    catch(IOException ex) {
        os.write(CodeRequest("500 Internal Server Error").getBytes());
        os.close();
        ex.printStackTrace();
        return;
    }

    System.out.println("Trying to send 200 OK");
    os.write(CodeRequest("200 OK").getBytes());
    os.flush();
    os.close(); // where os = clientSocket.getOutputStream();
    }

为什么客户端收不到服务器的响应?如果我中断了客户端的无限循环,那么 WebServer 就会正确地将数据记录到文件中。但是Client永远不会知道他的文件已经正常上传到服务器了。如果我在客户端注释掉这条语句:

// System.out.println(connection.getResponseCode());

然后Client正确退出循环结束。但是服务器甚至没有写信来安慰这个:

while((locr = is.read(locbuf)) > 0) {
  System.out.println("locr= "+locr);//this is NOT written to console
  osFile.write(locbuf, 0, locr);
}

服务器只写这个来安慰这个:

localExcString index out of range: -1

没有任何错误信息。

怎么了?

最佳答案

您的服务器示例代码未显示“is”的声明和初始化。 但是,我的猜测是,由于 session 保持 Activity 状态,对 is.read() 的调用将阻塞,直到某些数据到达。您已经在客户端中设置了内容长度,因此我希望在成功读取该数据量后看到读取循环完成。

关于Java,HttpUrlConnection。 getResponseCode() 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1697705/

相关文章:

windows - 如何创建 .BAT 文件以下载和解压缩 zip 文件?

unit-testing - 创建测试请求时如何模拟简单的 POST 正文

Python 网络服务器 : How to serve requests asynchronously

web - 远程服务器上的部署如何工作?

java - 第 20 行 : 'C: " "' when trying to publish my app on Google Play 上的错误无法识别的 xmltree 行

java - Java中替换字符串的内存高效方法

Java 非阻塞 HTTP 服务器

java - 在 Sun Java System Web 服务器中保留客户端 IP 地址

java.security.UnrecoverableKeyException : Given final block not properly padded

java - Android 应用程序在 onActivityResult 方法中崩溃