java - How to send post request with x-www-form-urlencoded body -
how in java, can send request x-www-form-urlencoded header
. don't understand how send body key-value, in above screenshot.
i have tried code:
string urlparameters = cafedra_name+ data_to_send; url url; httpurlconnection connection = null; try { //create connection url = new url(targeturl); connection = (httpurlconnection)url.openconnection(); connection.setrequestmethod("post"); connection.setrequestproperty("content-type", "application/x-www-form-urlencoded"); connection.setrequestproperty("content-length", "" + integer.tostring(urlparameters.getbytes().length)); connection.setrequestproperty("content-language", "en-us"); connection.setusecaches (false); connection.setdoinput(true); connection.setdooutput(true); //send request dataoutputstream wr = new dataoutputstream ( connection.getoutputstream ()); wr.writebytes (urlparameters); wr.flush (); wr.close ();
but in response, don't receive correct data.
as set application/x-www-form-urlencoded
content type data sent must format.
string urlparameters = "param1=data1¶m2=data2¶m3=data3";
sending part quite straightforward.
byte[] postdata = urlparameters.getbytes( standardcharsets.utf_8 ); int postdatalength = postdata.length; string request = "<url here>"; url url = new url( request ); httpurlconnection conn= (httpurlconnection) url.openconnection(); conn.setdooutput(true); conn.setinstancefollowredirects(false); conn.setrequestmethod("post"); conn.setrequestproperty("content-type", "application/x-www-form-urlencoded"); conn.setrequestproperty("charset", "utf-8"); conn.setrequestproperty("content-length", integer.tostring(postdatalength )); conn.setusecaches(false); try(dataoutputstream wr = new dataoutputstream(conn.getoutputstream())) { wr.write( postdata ); }
or can create generic method build key value pattern required application/x-www-form-urlencoded
.
private string getdatastring(hashmap<string, string> params) throws unsupportedencodingexception{ stringbuilder result = new stringbuilder(); boolean first = true; for(map.entry<string, string> entry : params.entryset()){ if (first) first = false; else result.append("&"); result.append(urlencoder.encode(entry.getkey(), "utf-8")); result.append("="); result.append(urlencoder.encode(entry.getvalue(), "utf-8")); } return result.tostring(); }
Comments
Post a Comment