html - How to send HTTP request in java? -
this question has answer here:
in java, how compose http request message , send http webserver?
you can use java.net.httpurlconnection.
example (from here), improvements. included in case of link rot:
public static string executepost(string targeturl, string urlparameters) { httpurlconnection connection = null; try { //create connection url 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.setdooutput(true); //send request dataoutputstream wr = new dataoutputstream ( connection.getoutputstream()); wr.writebytes(urlparameters); wr.close(); //get response inputstream = connection.getinputstream(); bufferedreader rd = new bufferedreader(new inputstreamreader(is)); stringbuilder response = new stringbuilder(); // or stringbuffer if java version 5+ string line; while ((line = rd.readline()) != null) { response.append(line); response.append('\r'); } rd.close(); return response.tostring(); } catch (exception e) { e.printstacktrace(); return null; } { if (connection != null) { connection.disconnect(); } } }
Comments
Post a Comment