标签云

微信群

扫码加入我们

WeChat QR Code

lets assume this URL...

http://www.example.com/page.php?id=10            

(Here id needs to be sent in a POST request)

I want to send the id = 10 to the server's page.php, which accepts it in a POST method.

How can i do this from within Java?

I tried this :

URL aaa = new URL("http://www.example.com/page.php");
URLConnection ccc = aaa.openConnection();

But I still can't figure out how to send it via POST


After trying for a while to get my hands on PostMethod it seems its actually now called HttpPost as per stackoverflow.com/a/9242394/1338936 - just for anyone finding this answer like I did :)

2018年07月17日05分53秒

I wish this answer was update, because its really useful.

2018年07月17日05分53秒

Juan (and Martin Lyne) thank you for the comments. I just updated the answer.

2018年07月17日05分53秒

Does your revised answer still use hc.apache.org ?

2018年07月18日05分53秒

you should add the imported libs

2018年07月17日05分53秒

This post is useful, but quite flawed. It took me 2 days to get it working. So to get it working you have to replace StandartCharsets.UTF8 with StandardCharsets.UTF_8 . boundaryBytes and finishBoundaryBytes need to get two additional hyphens which are NOT transmitted in the Content-Type, so boundaryBytes = ("--" + boundary + "\r\n").get... You also need to transmit the boundaryBytes once BEFORE the first field or the first field will be ignored!

2018年07月18日05分53秒

Updated my post to address the problems by Algoman

2018年07月17日05分53秒

Why out.write(finishBoundaryBytes); line need? http.connect(); will perform sending POST, isn't it?

2018年07月17日05分53秒

“Sending a POST request is easy in vanilla Java.” And then dozens of lines of code follow, compared to something like requests.post('http://httpbin.org/post', data = {'key':'value'}) in Python… I’m new to Java so this is a very strange use of the word “easy” to me :)

2018年07月18日05分53秒

It's relatively easier than what I expected considering it's Java :)

2018年07月17日05分53秒

what is encode function?

2018年07月18日05分53秒

and how to set 2 post data? Separate by colon, comma?

2018年07月17日05分53秒

encode(String) is deprecated. You have to use encode(String, String), which specifies the encoding type. Example: encode(rawData, "UTF-8").

2018年07月18日05分53秒

You may want to following at the end. This would make sure the request is finished and server gets a chance to process the response: conn.getResponseCode();

2018年07月17日05分53秒

Not work .... 0 errors, but not send..

2018年07月17日05分53秒

EntityUtils was helpful.

2018年07月17日05分53秒

Sorry, but you didn't catch any errors, you introduced them. Catching exceptions in a place where you can't handle them is plain wrong and e.printStackTrace() doesn't handle anything.

2018年07月18日05分53秒

java.net.ConnectException: Connection timed out: connect

2018年07月17日05分53秒

it it HttpURLConnection.setRequestMethod() :)

2018年07月17日05分53秒