【问题标题】:Unable to POST, HttpURLConnection defaults to GET无法 POST,HttpURLConnection 默认为 GET
【发布时间】:2017-06-12 17:13:26
【问题描述】:

我正在尝试 POST 到某个端点,但该 URL 不允许使用 GET 方法。使用 HTTPURLConnection 时,我将请求方法设置为 post 并将 doOutput 设置为 true。

但是由于某种原因,当我在 InputStream 上放置断点时(由于缺少文件而失败),请求方法是 GET,并且 doOutput 为假(只有 doInput 为真)。这会导致 404,method not allowed not found,表示方法 [get] 没有匹配的处理程序。为什么它会忽略我的设置并继续进行,就好像我什么都没输入一样?

String result = null;
    try {
        HttpURLConnection connection = (HttpURLConnection)new URL(baseUrl  + getTokenPath).openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((clientid + ":" + secret).getBytes()));
        connection.setDoOutput(true);


        DataOutputStream wr = new DataOutputStream (
                connection.getOutputStream ());

        wr.writeBytes ("grant_type=client_credentials");
        wr.flush ();
        wr.close ();

        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        result = response.toString();
        rd.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

【问题讨论】:

  • 404 不是“方法不允许”而是“未找到”,是拼写错误还是您看到了错误的错误?
  • 我的意思是 404,没有找到,那是一个错字。
  • 当您收到 404 时,就是这个意思。您请求的页面不存在于端点。因此,请仔细检查您发送帖子的地址。如果问题是您将收到另一个错误代码而不是 404 的方法。
  • 我已经知道了,我之前说过,当我在获取输入流之前设置断点时,HttpURLConnection 仍然是 GET,doOutput 为 false。它会忽略我插入的值并继续使用默认值。
  • 你能在endPoint中显示应该接收这篇文章的代码吗?

标签: java rest httpurlconnection


【解决方案1】:

在您从InputStream 读取所有数据之前,请勿关闭DataOutputStream

wr.close ();

关闭流会导致您断开连接。 Flush 足以发送POST 请求。

wr.flush ();

【讨论】:

    猜你喜欢
    • 2015-04-21
    • 2018-10-16
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    相关资源
    最近更新 更多