尝试 POST 到端点时出现未知协议错误

Getting unknown protocol error when trying to POST to endpoint

我正在尝试使用 post 方法连接到端点,但是我不断收到以下错误:

java.net.MalformedURLException: unknown protocol: localhost
at java.base/java.net.URL.<init>(URL.java:634)
at java.base/java.net.URL.<init>(URL.java:523)
at java.base/java.net.URL.<init>(URL.java:470)
at endpointtest.endpoint(endpointtest.java:23)
at main.main(endpoint.java:66)

我希望我的代码 return 基于 post 请求的响应,但事实并非如此。下面是我的代码:

public class endpointtest {

    public String endpoint(String urlStr, String username) {

        final StringBuilder response = new StringBuilder();

        try {
            //creating the connection
            URL url = new URL(urlStr);

            HttpClient client = HttpClient.newHttpClient();

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "Value");
            connection.connect();


            //builds the post body, adds parameters
            final DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            //out.writeBytes(toJSON(globalId)); 
            out.flush();
            out.close();

            //Reading the response
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputline;

            while ((inputline = in.readLine()) != null) {
                response.append(inputline);
            }
            in.close();

            connection.getResponseCode();
            connection.disconnect();

        } catch (final Exception ex) {

            ex.printStackTrace();
            System.out.println(" error ");
        }

        return response.toString();


    }

}
class main {

    public static void main(String[] args){
        endpointtest ep = new endpointtest();
        ep.endpoint("localhost:8080/endpoint","123");
    }
}

为什么会出现这个错误?基础错误还请见谅,我是web开发新手

您没有在 URL 字符串中包含协议 (http/https)。

改为ep.endpoint("http://localhost:8080/endpoint", "123"); 它应该可以工作。