【问题标题】:Getting unknown protocol error when trying to POST to endpoint尝试 POST 到端点时出现未知协议错误
【发布时间】:2020-12-03 03:53:19
【问题描述】:

我正在尝试使用 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)

我希望我的代码根据发布请求返回响应,但事实并非如此。以下是我的代码:

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 开发的新手

【问题讨论】:

  • http == 协议
  • 当您使用“localhost”时,您应该使用 http 而不是 https。并更改您的内容类型值。
  • @priyranjan 对内容类型应该更改为什么感到困惑
  • 看看这个链接javatpoint.com/content-type

标签: java http post request endpoint


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2016-03-09
    • 1970-01-01
    • 2016-04-22
    • 2014-04-17
    • 2018-04-27
    • 2013-03-03
    • 1970-01-01
    • 2018-06-21
    相关资源
    最近更新 更多