简体   繁体   English

如何使用HttpURLConnection将此HTTP / 1.1 POST用于Java?

[英]How do I get this HTTP/1.1 POST to work in Java using HttpURLConnection?

I am trying to send a HTTP/1.1 POST to http://uploaded.net/io/login , using HttpURLConnection , in order to login to the website with my username and password. 我试图使用HttpURLConnection将HTTP / 1.1 POST发送到http://uploaded.net/io/login ,以便使用我的用户名和密码登录到该网站。

For some reason it appears like byte[] postData is not being sent to the server. 出于某种原因,看起来像byte[] postData没有被发送到服务器。

I receive the response code and message 200 OK , but the server replies with the JSON-formatted error message {"err":"Please type in id and password"} as if I never actually sent the data. 我收到响应代码和消息200 OK ,但服务器回复JSON格式的错误消息{“err”:“请键入id和密码”} ,好像我从未真正发送过数据。

I've tried different methods (sending a String , byte[] etc., using different output writers) of sending the data but so far none of them have worked and I can't figure out where exactly it fails. 我已经尝试了不同的方法(发送一个Stringbyte[]等,使用不同的输出编写器)发送数据但到目前为止它们都没有工作,我无法弄清楚它究竟在哪里失败。

Here is the code snippet that I am working with: 这是我正在使用的代码片段:

package post;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;

public class PostTest {

    public static void login() throws MalformedURLException, IOException {
        String urlParameters = String.format("id=%s&password=%s", 
                URLEncoder.encode(Config.getProperty("account.1.username"), "UTF-8"), 
                URLEncoder.encode(Config.getProperty("account.1.password"), "UTF-8")
        );

        byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));

        URL url = new URL(Config.getProperty("login.url"));
        HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
        httpConn.setDoInput(true);
        httpConn.setDoOutput(true);
        httpConn.setUseCaches(false);
        httpConn.setRequestMethod("POST");
        httpConn.setRequestProperty("Content-Length", 
                    Integer.toString(postData.length));

        //prints: 26
        System.out.println(postData.length);
        //prints: id=test&password=123456789
        System.out.println(urlParameters);

        httpConn.getOutputStream().write(postData);
        httpConn.getOutputStream().flush();

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpConn.getInputStream()))) {
            for (String line; (line = reader.readLine()) != null;)
                System.out.println(line);
        }
    }
}

Live HTTP Headers (Firefox plugin) output: 实时HTTP标头 (Firefox插件)输出:

POST /io/login HTTP/1.1
Host: uploaded.net
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0
Accept: text/javascript, text/html, application/xml, text/xml, */*
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
X-Prototype-Version: 1.6.1
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://uploaded.net/
Content-Length: 20
Cookie: __utma=9[censored...]
Connection: keep-alive
  id=test&pw=123456789

HTTP/1.1 200 OK
[...]

Edit: Added the Firefox' Live HTTP Headers output which I used to see what data is being sent through POST. 编辑:添加了Firefox的Live HTTP Headers输出,我用它来查看通过POST发送的数据。

Is my assumption that byte[] postData is not sent correctly, if at all, correct? 我的假设是byte[] postData没有正确发送,如果有的话,对吗?

What changes do I have to make to get the login to work properly? 我必须进行哪些更改才能使登录正常工作?

Uhh, I've finally noticed my mistake. 呃,我终于发现了我的错误。 Hence I tried the first logins using my localhost/test.php where the parameter was password=<pw> I completly overlooked that the actual website I send the data to is using pw=<pw> instead. 因此我尝试使用我的localhost / test.php进行第一次登录,其中参数是password=<pw>我完全忽略了我发送数据的实际网站是使用pw=<pw>

After changing String.format("id=%s&password=%s", [...] to String.format("id=%s&pw=%s", [...] it works like a charm. 更改String.format("id=%s&password=%s", [...]String.format("id=%s&pw=%s", [...]它就像魅力一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM