基於Jave的Web服務工作機制(6)

來源:互聯網
上載者:User
web|web服務  parseUri 方法從請求行那裡得到URI。Listing 1.3 展示了parseUri 方法的用途。 parseUri 減縮請求中的第一個和第二個空格來獲得URI。

  Listing 1.3. The Request class' parseUri method

  private String parseUri(String requestString) {
  int index1, index2;
  index1 = requestString.indexOf(' ');

  if (index1 != -1) {
    index2 = requestString.indexOf(' ', index1 + 1);
    if (index2 > index1)
     return requestString.substring(index1 + 1, index2);
  }

  return null;
}

Response類Response表示一個HTTP響應。它的建構函式接受一個OutputStream對象,比如下面的:

  public Response(OutputStream output) {
  this.output = output;
  }
  Response 對象被HttpServer類的await方法構造,該方法被傳遞的參數是從socket那裡得到的OutputStream對象。

  Response類有兩個公用方法: setRequest和sendStaticResource. setRequest方法傳遞一個Request對象給Response對象。Listing 1.4中的代碼顯示了這個:

  Listing 1.4. The Response class' setRequest method

  public void setRequest(Request request) {
  this.request = request;
  }
  sendStaticResource 方法用來發送一個靜態資源,比如HTML檔案。Listing 1.5給出了它的實現過程:

  Listing 1.5. The Response class' sendStaticResource method

  public void sendStaticResource() throws IOException {
  byte[] bytes    = new byte[BUFFER_SIZE];
  FileInputStream fis = null;

  try {
    File file = new File(HttpServer.WEB_ROOT, request.getUri());
    if (file.exists()) {
      fis  = new FileInputStream(file);
      int ch = fis.read(bytes, 0, BUFFER_SIZE);

      while (ch != -1) {
        output.write(bytes, 0, ch);
        ch = fis.read(bytes, 0, BUFFER_SIZE);
      }
    }
    else {
      // file not found
      String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
        "Content-Type: text/html\r\n" +
        "Content-Length: 23\r\n" +
        "\r\n" +
        "<h1>File Not Found</h1>";
      output.write(errorMessage.getBytes());
    }
  }
  catch (Exception e) {
    // thrown if cannot instantiate a File object
    System.out.println(e.toString() );
  }
  finally {
    if (fis != null)
      fis.close();
  }
}



相關文章

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

Starter Package

SSD Cloud server and data transfer for only $2.50 a month

Get Started >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。