java - How to POST parameters and body in HttpURLConnection -
how do both @ same time?
the parameters query string parameters. body json.
connection.setrequestproperty("content-type", "application/json"); connection.setrequestproperty("accept", "application/json"); connection.setdooutput(true); connection.getoutputstream().write(parameters); connection.getoutputstream().write(sqldatabase.tostring().getbytes("utf-8"));
sqldatabase jsonobject, while parameters byte[];
obviously, depends on server interpreting post request. seems me want treat data html form includes file.
such form posts data multipart/form-data body. each parameter, whether query parameter or file data, separate part in multipart body. html 4 spec , rfc 2388 describe in detail.
creating multipart body can done javamail library:
list<bodypart> partlist = new arraylist<>(); parameterlist dispositionparams = new parameterlist(); (string queryparam : parameters.split("&")) { string[] nameandvalue = queryparam.split("=", 2); string name = nameandvalue[0]; string value = nameandvalue[1]; name = urldecoder.decode(name, "utf-8"); value = urldecoder.decode(value, "utf-8"); dispositionparams.set("name", name); contentdisposition disposition = new contentdisposition("form-data", dispositionparams); mimebodypart part = new mimebodypart(); part.setdisposition(disposition.tostring()); part.settext(value); partlist.add(part); } dispositionparams.set("database", name); contentdisposition disposition = new contentdisposition("form-data", dispositionparams); mimebodypart dbpart = new mimebodypart(); dbpart.setdisposition(disposition.tostring()); dbpart.setdatahandler(new datahandler( new bytearraydatasource(sqldatabase.tostring(), "application/json"))); partlist.add(dbpart); bodypart[] parts = partlist.toarray(new bodypart[0]); multipart body = new mimemultipart("form-data", parts); connection.setrequestproperty("content-type", body.getcontenttype()); connection.setrequestproperty("accept", "application/json"); connection.setdooutput(true); body.writeto(connection.getoutputstream());
Comments
Post a Comment