Hi I am trying to post json data to a PHP page by bellow code
URL obj = new URL(REST_URL);//(REST_URL + "?d_id=5&ds_remarks=" + et_text);
HttpURLConnection con = (HttpURLConnection) obj
.openConnection();
con.setRequestProperty("Content-type",
"application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
String body = "{";
body+="d_id:2,ds_remarks:" + et_text;
System.out.println(et_text);
body+="}";
DataOutputStream wr = new DataOutputStream(
con.getOutputStream());
wr.writeBytes(body);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
responseString = response.toString();
Log.d("GetCourse",
"Response Code: " + con.getResponseCode());
Log.d("Tag", "Response Stream : " + responseString);
con.disconnect();
System.out.println("=============================================");
return responseString;
I am getting response to PHP page, but not getting the parameter d_id or ds_remarks on PHP page. I am trying to fetch the parameter by using this code
$d_id = urldecode($_REQUEST['d_id']);
$ds_remarks = urldecode($_REQUEST['ds_remarks']);
Help me someone to fetch the parameter on PHP page.
Thanks
It seems you didnt added ur params in httppost like below :
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("d_id", "example"));
nameValuePairs.add(new BasicNameValuePair("ds_remarks", "example"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
opening just a connection will not post your parameters .
Edit :
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("d_id", "example"));
params.add(new BasicNameValuePair("ds_remarks", "example"));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
wr.write(formatQuery(params));
wr.flush();
wr.close();
os.close();
conn.connect();
private String formatQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
// append the params
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With