HttpURLConnection - 为什么只有在我们从连接

时间:2017-05-18 11:00:40

标签: java java-ee serversocket

为什么当我们尝试从连接中读取请求有效负载被发送到请求时的内容。在下面的代码中,如果是connection.getResponseCode();如果存在,请求由服务器接收,但如果它不存在,则请求未到达/正在发送。

如果在下面评论连接响应代码,它甚至不会抛出任何异常。

这基于Java 8。

            HttpURLConnection connection = null;
        URL url=new URL("http://...");
        connection = (HttpURLConnection) url.openConnection();
        String request="{\"language\":\"english\"}";
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("PUT");
        connection.setConnectTimeout(500);
        connection.setReadTimeout(300);

        connection.setRequestProperty("Content-Type", "application/json");

        outputStream = connection.getOutputStream();

        byte[] payload = request.getBytes();
        outputStream.write(payload);
        outputStream.flush();
        outputStream.close();

        //If commented request is not reaching server controller
        //if uncommented , request is reaching
        connection.getResponseCode();

0 个答案:

没有答案