我试图用 POST 调用我的 HttpServer 并在正文中发送一条消息,在服务器端我可以看到它被调用了两次,但我不知道为什么。这是客户端代码的一部分
String URL = "http://localhost:8081/" + path +"/service?session=" + sessionId;
connection = openConnection(URL, "POST");
OutputStream output = connection.getOutputStream();
output.write("Some Random body data".getBytes());
output.close();
stream = connection.getInputStream();
stream.close();
connection.disconnect();
在服务器端,我可以看到该服务被调用了两次。我认为它必须对我的 OutputStream 和 InputStream 做一些事情,但如果我不调用输入流,它不会在任何时候调用该服务。
编辑!!!这是更多代码 public class Server {
private static final int BASE_PORT = 8081;
public static void main(String[] args) {
try{
InetSocketAddress address = new InetSocketAddress(BASE_PORT);
HttpServer server = HttpServer.create(address, 0);
server.createContext("/", new PathDelegator());
server.setExecutor(Executors.newCachedThreadPool());
server.start();
System.out.println("Server is listening on : " + BASE_PORT);
}catch(IOException e){
e.printStackTrace();
}
}
}
public class PathDelegator implements HttpHandler{
public void handle(HttpExchange exchange) throws IOException {
String URI = exchange.getRequestURI().toString();
if(URI.indexOf("/session") != -1){
//Call ServiceHandler
System.out.println("Call ServiceHandler");
serviceHandler(exchange, "some session key");
}
}
private void serviceHandler(HttpExchange exchange, String sessionId) throws IOException{
String requestMethod = exchange.getRequestMethod();
OutputStream responseBody = exchange.getResponseBody();
if(requestMethod.equalsIgnoreCase("POST")){
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/plain");
InputStream stream = exchange.getRequestBody();
int b = 0;
StringBuffer buffer = new StringBuffer();
while((b = stream.read()) != -1){
buffer.append((char)b);
}
System.out.println("body data: " + buffer.toString());
exchange.sendResponseHeaders(200, 0);
}else {
exchange.sendResponseHeaders(400, 0);
}
responseBody.close();
}
}
public class ClientTest {
@Test
public void shouldBeAbleToPostToService(){
try {
String SCORE_URL = "http://localhost:8081/service?session=" + sessionId;
connection = openConnection(URL, "POST");
OutputStream output = connection.getOutputStream();
output.write("Some body data".getBytes());
output.close();
stream = connection.getInputStream();
stream.close();
connection.disconnect();
fail("Not implemented yet!");
} catch (IOException e) {
e.printStackTrace();
}
}
private HttpURLConnection openConnection(String url, String method) throws IOException{
URL connectionURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection)connectionURL.openConnection();
connection.setRequestMethod(method);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
return connection;
}
}
最后我看到System.out.println("body data: " + buffer.toString());
输出了两次