Sending Java POST request without calling getInputStream()
I would like to send a POST request in Java. At the moment, I do it like this:
U开发者_如何转开发RL url = new URL("myurl");
URLConnection con = url.openConnection();
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
ps.println("key=" + URLEncoder.encode("value"));
// we have to get the input stream in order to actually send the request
con.getInputStream();
ps.close();
I do not understand why I have to call con.getInputStream() in order to actually send the request. If I do not call it, the request is not sent.
Is there a problem using PrintStream? It should not matter if I take a PrintStream, PrintWriter or something else, right?
URL represents some source.
URLConnection represents a connection to the resource.
you need call connection.connect() to connect the connection
Try to add
con.setDoInput (false);
before writing to the output.
P.S.: and you should also call con.connect () as swanliu says.
Update
This is what I came up with
private static final void sendPostRequest (final String urlAddress, String key, String value) throws Exception
{
URL url = new URL (urlAddress);
URLConnection con = url.openConnection ();
con.setDoOutput (true);
con.setDoInput (false);
PrintStream ps = new PrintStream (con.getOutputStream ());
ps.println (key + "=" + URLEncoder.encode (value, "UTF-8"));
ps.flush ();
con.connect ();
ps.close ();
}
I checked with WireShark that a tcp connection is being established and that closed. But don't know how check that the server received the request. If you have a quick way to check it you may try that code.
I think a post of another thread answered my question. Sorry, but I found it too late. You can find it here.
PS: Unfortunately, Stackoverflow added my last answer to the question as a comment, because my answer was too short. And it is not possible to mark a comment as the correct answer... Hope this one is long enough :-)
I think this is the easiest way.
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
ps.print("&client_id="+ 2);
ps.print("&amount="+10);
ps.flush();
ps.close();
精彩评论