Can I Fetch Data From URL Using POST Method In Android?
I want to fetch data from a URL using the POST method. I already fetched data using the GET method. Now I want to do it with the POST method. When I click on the button I don't get
Solution 1:
Use this for POST request using HttpURLConnection, you can add or remove properties based on your requirement:
URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(7000);
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1", paramValue1));
params.add(new BasicNameValuePair("param2", paramValue2));
OutputStream outputStream = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
outputStream.close();
conn.connect();
Here is getQuery() method :
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
Post a Comment for "Can I Fetch Data From URL Using POST Method In Android?"