Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java HttpURLConnection-使用Cookie发布_Java_Cookies_Post_Httpurlconnection - Fatal编程技术网

Java HttpURLConnection-使用Cookie发布

Java HttpURLConnection-使用Cookie发布,java,cookies,post,httpurlconnection,Java,Cookies,Post,Httpurlconnection,我正在尝试发送带有cookies的post请求。代码如下: try { String query = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("value", "UTF-8"); String cookies = "session_cookie=value"; URL url = new URL("https://myweb"); HttpsURLConnection conn =

我正在尝试发送带有cookies的post请求。代码如下:

try {

    String query = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("value", "UTF-8");
    String cookies = "session_cookie=value";
    URL url = new URL("https://myweb");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    conn.setRequestProperty("Cookie", cookies);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    out.writeBytes(query);
    out.flush();
    out.close();

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String decodedString;
    while ((decodedString = in.readLine()) != null) {
        System.out.println(decodedString);
    }
    in.close();

    // Send the request to the server
    //conn.connect();
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
问题是发送请求时没有cookies。如果我只提出: 连接();并且不发送数据,cookie发送正常。
我无法准确地检查发生了什么,因为连接是通过SSL的。我只检查响应。

根据
URLConnection
javadoc:

The following methods are used to access the header fields and the 
contents AFTER the connection is made to the remote object:

* getContent
* getHeaderField
* getInputStream
* getOutputStream

您是否确认在上面的测试用例中,请求根本就没有到达服务器?我看到您在
getOutputStream()
之后调用了
connect()
,并且被注释掉了。如果取消对它的注释并在调用
getOutputStream()
之前向上移动,会发生什么情况

谢谢!我再次尝试在服务器上重写php代码,结果非常好。我发布的代码还可以。我想问题出在服务器上(我可以写$\u POST[$key]而不是$\u POST['key']之类的东西吗?)。