JAVA API http服务器 - 获取url参数并停止服务器

时间:2014-12-12 01:38:10

标签: java api httpserver

我正在玩这个http服务器示例,我不得不提问:

1)而不是这个静态答案字符串" Hello world",我想用URL的单词更改字符串。因此,如果我输入http://localhost:8004/example并重新加载页面,则应显示example

2)如何停止服务器?因为如果我再试一次,它总是说端口已经绑定了。

有人有想法吗?

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

/*
 * a simple static http server
*/
public class SimpleHttpServer {

  public static void main(String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(8004), 0);
    server.createContext("/test", new MyHandler());
    server.setExecutor(null); // creates a default executor
    server.start();
  }

  static class MyHandler implements HttpHandler {
    public void handle(HttpExchange t) throws IOException {
      String response = "Hello world";
      t.sendResponseHeaders(200, response.length());
      OutputStream os = t.getResponseBody();
      os.write(response.getBytes());
      os.close();
    }
  }
}

2 个答案:

答案 0 :(得分:1)

如果我理解了您的问题,您可以先拨打response然后拨打getRequestURI()来设置getPath()

String response = t.getRequestURI().getPath();

至于停止服务器,你可以打电话

System.exit(0);

将关闭JVM。

答案 1 :(得分:0)

启动服务器,然后main方法终止,将服务器留在后台线程中,继续占用端口。您需要等到某个事件(例如主线程被中断)并停止服务器。此外,您可以使用t.getRequestURI()。getPath()获取请求URI的路径组件。

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class SimpleHttpServer {
  public static void main(String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(8004), 0);
    server.createContext("/test", new MyHandler());
    server.setExecutor(null); // creates a default executor
    server.start();

    try
    {
        while(!Thread.currentThread().isInterrupted())
            Thread.sleep(100);
    }
    catch(InterruptedException e)
    {
    }
    finally
    {
        server.stop(0);
    }
  }
  static class MyHandler implements HttpHandler {
    public void handle(HttpExchange t) throws IOException {
      String response = t.getRequestURI().getPath();
      t.sendResponseHeaders(200, response.length());
      OutputStream os = t.getResponseBody();
      os.write(response.getBytes());
      os.close();
    }
  }
}