I've tried several things but my android app is not sending post parameters. I run the app on a virtual device. This is the code:
#Override
public void run() {
try{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(page);
HttpParams httpParams = client.getParams();
httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
obj.put("username", "abcd");
obj.put("password", "1234");
post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
BufferedReader reader = new BufferedReader(isr);
String line = "";
while((line = reader.readLine()) != null){
System.out.println(line);
}
}catch(Exception e){
e.printStackTrace();
}
}
It should send a post request to a PHP page. This page displays the output of the POST array:
<?php
print_r($_POST);
?>
When I run the app, it displays an empty array.
thats because you're sending JSON
standard php $_POST is build from key-value pairs
so you should post key1=value1&key2=value2
or you should read from
$HTTP_RAW_POST_DATA
or
<?php $postdata = file_get_contents("php://input"); ?>
and use
json_decode( $postdata );
PHP will not automatically decode json for you
you can also use another approach and POST your json like data=YourJsonCode
and then decode it using json_decode( $_POST['data'] );
Try sending url encoded name/value pairs. You can also use EntityUtils to convert the response to a String for you.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(page);
HttpParams httpParams = client.getParams();
httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
post.setHeader("Content-Type","application/x-www-form-urlencoded");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("username", "abcd"));
formParams.add(new BasicNameValuePair("password", "1234"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams,HTTP.UTF_8);
post.setEntity(entity);
HttpResponse httpResponse = client.execute(post);
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
Problem solved. There was a htaccess file that redirected all non www pages.
Related
I want to make a post from my android application and insert into my database. My first approach was to send a post from my application and just show the value but it did not work.
My code from the application is
public void postData() {
HttpClient Client = new DefaultHttpClient();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("regid", "sID"));
nameValuePairs.add(new BasicNameValuePair("etc", "sETC"));
try {
String SetServerString = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://your-url.com/script.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = httpclient.execute(httppost, responseHandler);
} catch(Exception ex) {
// failed
}
}
The php code is
<?php
include 'db.inc.php';
$device_token = urldecode($_POST['regid']);
echo $device_token;
?>
Replace your lines
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = httpclient.execute(httppost, responseHandler);
By
HttpResponse response = httpclient.execute(httppost);
You can check response in android side using
String responseStr = EntityUtils.toString(response.getEntity());
System.out.println(responseStr);
Use following PHP code to get values.
<?php
$value1 = $_POST["regid"];
$value2 = $_POST["etc"];
echo $value1;
?>
I'm trying to get token from sever response it works great with postMan , but when debug it with android it gets error:
unsupported_grant_type
here is my code:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(LoginURL);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
// post.setHeader("Accept", "application/x-www-form-urlencoded");
JSONObject obj = new JSONObject();
try {
obj.put("grant_type", "password");
obj.put("password", PasswordEditText);
obj.put("username", EmailEditText+"gfg");
post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
results = EntityUtils.toString(entity);
myObject = new JSONObject(results);
finally I have found the solution :
replace :
post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
With:
post.setEntity(new StringEntity("grant_type=password&username=0000#gmail.com&password=00000", "UTF-8"));
I'm making an android app and run it on the simulator. All post parameters on the server are empty when I send a http post request. This is code in the android app:
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(page);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStreamReader inreader = new InputStreamReader(response.getEntity().getContent());
BufferedReader reader = new BufferedReader(inreader);
String line = "";
while((line = reader.readLine()) != null){
System.out.println(line);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
And this is the code on the server:
<?php
print_r($_POST);
?>
It returns an empty php array when I run it on the simulator.
Put www in the request url and it was solved. There was a htaccess file that corrected all url`s without www.
Volley Library(sim-official from google) is better, http, https etc.
https://developers.google.com/live/shows/474338138
There's a very mini sample here:https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/Act_SimpleRequest.java
There's the same question like you here: Optimizing HTTP requests in android
For example if we need to send content which is in this format , how do we do it
{"name1":[{"name11":"value11"},{"name11":"value12"},{"name11":"value13"}],"name2":value2}
I know how to set the basic kind
{"name1":"value1","name2":value2}
NameValuePair[] nameValuePairs = new NameValuePair[2];
nameValuePairs[0]= new BasicNameValuePair("name1", "value1");
nameValuePairs[1] = new BasicNameValuePair("name2", value2);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
How can we achieve nesting
Please see this question as it has a couple of answers that should help you. Here is a brief snippet from the answers code:
HttpPost request = new HttpPost(serverUrl);
request.setEntity(new ByteArrayEntity(
postMessage.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);
The other answer says you can do something like this:
protected void sendJson(final String email, final String pwd) {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try{
HttpPost post = new HttpPost(URL);
json.put("email", email);
json.put("password", pwd);
StringEntity se = new StringEntity( "JSON: " + json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
catch(Exception e){
e.printStackTrace();
createDialog("Error", "Cannot Estabilish Connection");
}
}
I'm trying to submit some data formatted as a JSONObject to a web server. My understanding was that this is done with an httpclient on android and then a php file on the server. If that's not the case stop here and correct me, otherwise here's how i'm trying to send the data:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myhost/data.php");
try {
String UN = username.getText().toString();
String PW = password.getText().toString();
String jString = "{\"login\": { \"username\": \""+UN + "\",\"password\": \""+PW+"\"}}";
JSONDATA = new JSONObject(jString);
//JSONDATA = new JSONObject();
//JSONDATA.put("username", UN);
//JSONDATA.put("password", PW);
should i be using: httppost.setEntity(new UrlEncodedFormEntity(JSONDATA));
or should i be doing it like so:
StringEntity se = new StringEntity(JSONDATA.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
HttpEntity entity;
entity = se;
httppost.setEntity(entity);
HttpResponse response;
response = httpclient.execute(httppost);
The question really is how are you planning to pull the data out on the server? What does your PHP look like? What may be easiest is to just pass the JSON as a parameter:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myhost/data.php");
try {
String UN = username.getText().toString();
String PW = password.getText().toString();
String jString = "{\"login\": { \"username\": \""+UN + "\",\"password\":\""+PW+"\"}}";
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("value", jString));
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response;
response = httpclient.execute(httppost);
and then on the server side you can just do
<?php
$obj = json_decode($_POST['value']);
to retrieve it.