Java httpurlconnection – post with cookie
•
Java
I want to send a release request with cookies This is the code:
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(); }
The problem is that the request was not sent with a cookie If I only do: conn.connect(); And without sending data, the cookie is sent I can't correctly check what happened because the connection is cheating SSL I only check the response
Solution
According to 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
Are you sure that in the above test case, the request is reaching the server? I see that you have called connect () after getOutputStream () and have been commented off. What happens if you uncomment and move up before calling getoutputstream()?
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码