【问题标题】:HttpUrlConnection class performs GET despite setting POST as method type尽管将 POST 设置为方法类型,但 HttpUrlConnection 类仍执行 GET
【发布时间】:2017-08-31 13:13:41
【问题描述】:

我正在尝试使用同时具有 GET 和 POST 请求处理程序的 API。 当我尝试执行 GET 请求时,如下所示:

HttpsURLConnection httpURLConnection = (HttpsURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();

我得到了正确的 Cookies 以及 HTML 响应。

但现在我尝试在同一个 url 上执行 POST 请求,如下所示:

String postBody = "__RequestVerificationToken=" + __RequestVerificationToken + "&Username=" + userName
            + "&Password=" + passWord;
byte[] postData = postBody.getBytes(StandardCharsets.UTF_8);

HttpsURLConnection httpURLConnection = (HttpsURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Length", Integer.toString(postData.length));
httpURLConnection.setUseCaches(false);

/**
 * write the request body as bytes
 */
OutputStream os = httpURLConnection.getOutputStream();
os.write(postBody.getBytes());
os.flush();
os.close();

我在 CookiesHTML 响应 中得到的所有内容与我之前在 GET 请求中收到的内容相同。

有人能解释一下发生了什么吗?

【问题讨论】:

    标签: java post https get httpurlconnection


    【解决方案1】:

    您需要添加 httpURLConnection.setDoInput(true);

    <!-- language: java -->
    String postBody = "__RequestVerificationToken=" + __RequestVerificationToken + "&Username=" + userName
                + "&Password=" + passWord;
    byte[] postData = postBody.getBytes(StandardCharsets.UTF_8);
    
    HttpsURLConnection httpURLConnection = (HttpsURLConnection) url.openConnection();
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setDoInput(true);
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    httpURLConnection.setRequestProperty("charset", "utf-8");
    httpURLConnection.setRequestProperty("Content-Length", Integer.toString(postData.length));
    httpURLConnection.setUseCaches(false);
    
    /**
     * write the request body as bytes
     */
    OutputStream os = httpURLConnection.getOutputStream();
    os.write(postBody.getBytes());
    os.flush();
    os.close();
    

    【讨论】:

    • 具体在哪里?在 POST 调用时?
    • ` httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); ... `
    猜你喜欢
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 2017-01-04
    • 2011-09-04
    相关资源
    最近更新 更多