My PHP code:
<?php
$data = 'basic';
if( $_POST["tag"]){
$data = $data.$_POST['tag'];
}
if( $_GET["tag"]){
$data = $data.$_GET['tag'];
}
echo $data;
?>
My Android code:
String url = http: //<IP>/sreeweb/sample.php;
List params = new ArrayList();
params.add(new BasicNameValuePair("tag", "services"));
InputStream is = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
httpPost.setHeader("Accept", "*/*");
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.d("msg", "res : " + httpResponse.getStatusLine().getStatusCode()); //200
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
Log.d("msg", "" + is);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader;
StringBuilder stringBuilder = null;
try {
reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "
");
}
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String result = stringBuilder.toString();
Log.e(TAG, result);
The GET method is working. But the POST method is not working when I invoke it from Android. It is invoking the PHP page but the values are not being passed.
But when I invoke POST method from a REST client via Chrome (chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo/RestClient.html) it works and the values are passing in properly. But why not from Android?
I even tried using the following code, but it doesn't work:
try {
String data = URLEncoder.encode("tag", "UTF-8") + "=" + URLEncoder.encode("services", "UTF-8");
URL url = new URL(finalUrl);
HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept", "*/*");
// Allow Inputs
conn.setDoInput(true);
conn.setDoOutput(true);
// Use a post method.
conn.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
Log.e(TAG, "postMethod " + sb.toString());
return sb.toString();
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}