Menu

Sending Parameters to URL or web service in POST Method

Java, Webservice By Dec 26, 2014 No Comments
Below code snippet
explains how to send parameters to a web url in the POST method.
URL url = new URL(“http://testulr/searchuser”);
HttpURLConnection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(“POST”);
urlConnection.setDoOutput(true);
String
params=”userid=”+userid+”&username=”+name;
OutputStream
out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(params);
writer.flush();
out.close();
InputStream
in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder
st = new StringBuilder();
String
line = “”;
while
((line = reader.readLine()) != null) {
                st.append(line);
}
System.out.println(“Result: “+st);
urlConnection.disconnect();
If the url is secured then replace HttpURLConnection
class with HttpsURLConnection in the above code.

No Comments

Leave a comment

Hi, Welcome here.
JOIN OUR NEWSLETTER
And get notified everytime we publish a new blog post.