Java Http Post Request没有输出:没有响应或错误

时间:2019-04-02 10:43:57

标签: html java-8 http-post

我正在尝试创建一个HTTP发布请求,它应该也可以正常工作,但是页面没有响应(使用浏览器可以正常工作)。代码如下:

            try {
                URL site = new URL("https://google.com");
                HttpsURLConnection conn = (HttpsURLConnection) site.openConnection();
                conn.setConnectTimeout(1000);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Host", "www.example.com");
                conn.setRequestProperty("User-Agent",
                        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0");
                conn.setRequestProperty("Accept-Language", "en-EN,en;q=0.8,en-US;q=0.5,en;q=0.3");
                conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                conn.setRequestProperty("Referer", "https://google.com");
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("Connection", "close");
                conn.setRequestProperty("Upgrade-Insecure-Requests", "1");
                conn.setInstanceFollowRedirects(true); 
                HttpsURLConnection.setFollowRedirects(true);

                for (String string : this.Cookie) {
                //my own working cookies    conn.setRequestProperty("Cookie", string);
                }

                OutputStream os = conn.getOutputStream();
                os.write(post_request.getBytes());
                os.flush();

                if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                    throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
                }

                BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

                String output;
                System.out.println("Output from Server .... \n");
                while ((output = br.readLine()) != null) {
                    System.out.println(output);
                }
                conn.disconnect();

            } catch (IOException ex) {
                System.out.println("Unable to reach the site: Because of: " + ex.getMessage());
            }

当我的代码发送请求时,如果我尝试获取响应代码或阅读HTML代码,则会得到:

Unable to reach the site Because of: connect timed out

如果post参数错误,我也期望页面的响应代码和HTML输出,但是结果不是预期的。 如果我删除尝试获取响应代码的尝试和使用BufferedReader获取HTML响应代码的尝试,它不会超时,但是无论如何都不会发送发布请求。

0 个答案:

没有答案