服务两次

时间:2013-09-26 19:28:33

标签: java http

我试图通过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做一些事情,但如果我不调用输入流,它不会随时调用该服务。

EDIT !!! 这是一些更多的代码     公共类服务器{

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

}

Finallty我看到System.out.println("body data: " + buffer.toString());输出了两次

1 个答案:

答案 0 :(得分:0)

好吧,我终于弄清楚发生了什么...... 我有一个方法     public synchronized boolean addValue(int id, int value){ Integer previous = values.put(id, value); return previous.intValue() != value; }

问题是第一次,put会返回一个NULL值,一旦我处理了这个方法,错误就不会再发生了。