How to use HttpURLConnection POST data to web server?
Here is one sample.
...
public static String excutePost(String targetURL, String urlParameters)
{
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 ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
...
The urlParameters is a URL encoded string.
String urlParameters =
"fName=" + URLEncoder.encode("???", "UTF-8") +
"&lName=" + URLEncoder.encode("???", "UTF-8")
Most Viewed java Faqs
- How to use HttpURLConnection POST data to web server?(14985)
- What is runtime polymorphism in Java?(9463)
- What is String literal pool?(8786)
- Can the run() method be called directly to start a thread?(8234)
- How to add BASIC Authentication into HttpURLConnection?(7469)
- Can transient variables be declared as 'final' or 'static'?(6298)
- Can static methods be overridden?(4958)
Most Recent java Faqs
- What is the difference between an enum type and java.lang.Enum?
- Which replace function works with regex?
- Why does TreeSet.add throw ClassCastException?
- What is variable hiding and shadowing?
- Can private method be overridden?
- How to enable JDBC tracing?
- How to Retrieve Automatically Generated Keys in JDBC?