HttpUrlConnect不发送发布请求作为线程的一部分

时间:2019-07-29 21:17:08

标签: java rest

我正在尝试将http发布请求作为并发线程的一部分发送到应用程序启动。

下面的代码显示了我现在拥有的当前代码。我尝试使用Baeldung和类似教程网站中的代码,但似乎无法正常工作。

 public static void main(String[] args) throws Exception {
    HttpURLConnection con = (HttpURLConnection) new URL("http://localhost:5000/").openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json; utf-8");
    con.setDoOutput(true);
    String jsonInputString = "{\"status\": \"UP\"}";
    OutputStream os = con.getOutputStream();

    //random code here not involved with this quesiton

    new Thread(new Runnable() {
      public void run() {
        while (true) {
          try {

            os.write(jsonInputString.getBytes());
            os.flush();
        }
          catch (Exception exception) {
            System.out.println("Its not working");
          }
        }

      }
    }).start();
    launch(args);

当我在浏览器中输入localhost:5000时,它说它无法连接。

1 个答案:

答案 0 :(得分:0)

第一步,请确保本地主机在端口5000上运行,然后在常规浏览器中转到http://localhost:5000/,如果该端口不起作用,则需要确保您的计算机正确在端口5000上提供了页面。

如果这有效,则HTTP请求可能由于未连接到具有有效SSL证书的服务器而被阻止,您可以尝试将网页更改为http://www.google.com并查看是否得到响应。