国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 服務(wù)器 > Win服務(wù)器 > 正文

基于Jave的Web服務(wù)工作機(jī)制(6)

2024-09-10 00:02:38
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友
 parseUri 方法從請(qǐng)求行那里得到URI。Listing 1.3 展示了parseUri 方法的用途。 parseUri 減縮請(qǐng)求中的第一個(gè)和第二個(gè)空格來(lái)獲得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表示一個(gè)HTTP響應(yīng)。它的構(gòu)造函數(shù)接受一個(gè)OutputStream對(duì)象,比如下面的:

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

  Response類有兩個(gè)公共方法: setRequest和sendStaticResource. setRequest方法傳遞一個(gè)Request對(duì)象給Response對(duì)象。Listing 1.4中的代碼顯示了這個(gè):

  Listing 1.4. The Response class' setRequest method

  public void setRequest(Request request) {
  this.request = request;
  }
  sendStaticResource 方法用來(lái)發(fā)送一個(gè)靜態(tài)資源,比如HTML文件。Listing 1.5給出了它的實(shí)現(xiàn)過程:

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

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 伊宁县| 宾川县| 中山市| 珠海市| 临西县| 古交市| 五台县| 勐海县| 洛扎县| 明星| 鲁山县| 文成县| 平凉市| 丽水市| 武强县| 顺昌县| 克拉玛依市| 永安市| 久治县| 甘肃省| 崇明县| 浦城县| 吉林省| 克东县| 大丰市| 湟源县| 怀远县| 东山县| 南昌县| 中宁县| 施秉县| 潍坊市| 平遥县| 宾阳县| 九江县| 怀集县| 连南| 万州区| 无极县| 静乐县| 英吉沙县|