基于Jave的Web服务工作机制(6)

bobo爱婷儿

bobo爱婷儿

2016-02-19 14:02

给自己一点时间接受自己,爱自己,趁着下午茶的时间来学习图老师推荐的基于Jave的Web服务工作机制(6),过去的都会过去,迎接崭新的开始,释放更美好的自己。
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(' ');

(本文来源于图老师网站,更多请访问https://m.tulaoshi.com/webkaifa/)

  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 Foundrn" +
        "Content-Type: text/htmlrn" +
        "Content-Length: 23rn" +
        "rn" +
        "h1File 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();
  }
}

(本文来源于图老师网站,更多请访问https://m.tulaoshi.com/webkaifa/)

展开更多 50%)
分享

猜你喜欢

基于Jave的Web服务工作机制(6)

Web开发
基于Jave的Web服务工作机制(6)

基于Jave的Web服务工作机制(7)

Web开发
基于Jave的Web服务工作机制(7)

s8lol主宰符文怎么配

英雄联盟 网络游戏
s8lol主宰符文怎么配

基于Jave的Web服务工作机制(4)

Web开发
基于Jave的Web服务工作机制(4)

基于Jave的Web服务工作机制(5)

Web开发
基于Jave的Web服务工作机制(5)

lol偷钱流符文搭配推荐

英雄联盟 网络游戏
lol偷钱流符文搭配推荐

基于Jave的Web服务工作机制(3)

Web开发
基于Jave的Web服务工作机制(3)

基于Jave的Web服务工作机制(1)

Web开发
基于Jave的Web服务工作机制(1)

lolAD刺客新符文搭配推荐

英雄联盟
lolAD刺客新符文搭配推荐

压缩PowerPoint2003里面的图片以缩小体积

压缩PowerPoint2003里面的图片以缩小体积

2018,一直在等侯 - QQ伤感分组

2018,一直在等侯 - QQ伤感分组
下拉加载更多内容 ↓