0

我从一个客户端向服务器发出两个请求,客户端在方法 httpclient.execute(httpPost) 的第二次执行时挂起;如果我为每个请求创建新客户端一切正常。如果我 POST 到谷歌(例如),一切都很好。有什么问题?

服务器:

public static void main(String[] args) throws IOException {
    HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 8080),2);
    server.setExecutor(Executors.newFixedThreadPool(5));
    HttpContext context = server.createContext("/", new GlobalHandler());
    context.getFilters().add(new GlobalFilter());
    server.createContext("/setup.exe", new GetFileHandler());
    server.start();
}


private static class GlobalHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange t) throws IOException {
        Headers headers = t.getRequestHeaders();

        System.out.println(headers.entrySet());

        System.out.println(t.getHttpContext());
        System.out.println(t.getRequestURI());
        System.out.println(t.getProtocol());
        System.out.println(t.getRequestMethod());
        String resp = "Hello";
        if (Objects.equals(t.getRequestMethod(), "POST")) {
            System.out.println("POST");
            Map params = (Map) t.getAttribute("parameters");
            resp = params.toString();
            System.out.println(params);
        }

        byte[] bytesToWrite = resp.getBytes("UTF-8");
        t.sendResponseHeaders(200, bytesToWrite.length);
        OutputStream os = t.getResponseBody();
        os.write(bytesToWrite);
    }
}

客户:

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1 * 1000).build();
    httpclient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

    for(int i= 0;i<2;i++) {

        HttpPost httpPost = new HttpPost("http://google.com");
        httpPost.addHeader("Connection","keep-alive");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "вг"));
        nvps.add(new BasicNameValuePair("password", "аб"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        CloseableHttpResponse response2 = httpclient.execute(httpPost);

        try {
            System.out.println(response2.getStatusLine());
            HttpEntity entity2 = response2.getEntity();
            if(entity2.getContentLength() >0) {
                byte[] content = new byte[(int) entity2.getContentLength()];
                entity2.getContent().read(content);
                System.out.println(new String(content, "UTF-8"));
            }
            EntityUtils.consume(entity2);
        } finally {
            response2.close();

        }
    }
    httpclient.close();
4

0 回答 0