我有一个GPS设备,该设备通过给定端口通过http连接,可以从http服务器发送和接收数据。为了进行测试,我创建了一个简单的java http服务器,该服务器读取请求并发送响应。这是我的代码:
public class simpleHTTPServer {
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(9090), 0);
HttpContext context = server.createContext("/");
context.setHandler(simpleHTTPServer::handleRequest);
server.start();
}
private static void handleRequest(HttpExchange exchange) throws IOException {
// URI requestURI = exchange.getRequestURI();
printRequestInfo(exchange);
System.out.println("sending command..");
String response = "123456";
exchange.sendResponseHeaders(200, response.getBytes().length);
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
private static void printRequestInfo(HttpExchange exchange) {
System.out.println("-- headers --");
Headers requestHeaders = exchange.getRequestHeaders();
requestHeaders.entrySet().forEach(System.out::println);
System.out.println("-- principle --");
HttpPrincipal principal = exchange.getPrincipal();
System.out.println(principal);
System.out.println("-- HTTP method --");
String requestMethod = exchange.getRequestMethod();
System.out.println(requestMethod);
System.out.println("-- query --");
URI requestURI = exchange.getRequestURI();
String query = requestURI.getQuery();
System.out.println(query);
}
}
实际上,该设备确认它已与http服务器(http://mydomain:9090)连接并不断发送数据,但是在我运行的http服务器程序中,我无法从此设备获得任何请求。
要验证这一点,我在端口9090上进行了tcpdump验证,并使用Wireshark验证了此设备正在成功发送请求。我有点困惑,因为Wireshark显示请求是通过TCP协议发出的。那么我如何在Java中通过HTTP读取此请求?
答案 0 :(得分:-1)
HTTP通过TCP运行。话说回来。 您可以在此处做一些事情来调试这种情况: