PHP Post Android Post - java

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;
?>

Related

HttpPost Posting Complex JSONObject in the Body of the Request

I was wondering, using HttpClient and HttpPOST is there a way to post a complex JSON object as the body of the request? I did see an example of posting a simple key/value pair in the body (as shown below from this link: Http Post With Body):
HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("paramName", "paramValue"));
request.setEntity(new UrlEncodedFormEntity(pairs ));
HttpResponse resp = client.execute(request);
However, I would need to post something like the following:
{
"value":
{
"id": "12345",
"type": "weird",
}
}
Is there a way for me to accomplish this?
ADDITIONAL INFORMATION
Doing the following:
HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");
String json = "{\"value\": {\"id\": \"12345\",\"type\": \"weird\"}}";
StringEntity entity = new StringEntity(json);
request.setEntity(entity);
request.setHeader("Content-type", "application/json");
HttpResponse resp = client.execute(request);
results in an empty body on the server... hence i get a 400.
Thanks in advance!
HttpPost.setEntity() accepts StringEntity which extends AbstractHttpEntity. you can set it with any valid String of your choice:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost request = new HttpPost("www.example.com");
String json = "{\"value\": {\"id\": \"12345\",\"type\": \"weird\"}}";
StringEntity entity = new StringEntity(json);
entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
request.setEntity(entity);
request.setHeader("Content-type", "application/json");
HttpResponse resp = client.execute(request);
This worked for me!
HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");
String json = "{\"value\": {\"id\": \"12345\",\"type\": \"weird\"}}";
StringEntity entity = new StringEntity(json);
entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
request.setEntity(entity);
request.setHeader("Content-type", "application/json");
HttpResponse resp = client.execute(request);

Following redirects in HTTPResponse Android

I need to follow redirects given to me by HTTPost. When I make an HTTPost, and try to read the response, I get the redirect's page html. How can I fix this? Code:
public void parseDoc() {
final HttpParams params = new BasicHttpParams();
HttpClientParams.setRedirecting(params, true);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"https://secure.groupfusion.net/processlogin.php");
String HTML = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("referral_page",
"/modules/gradebook/ui/gradebook.phtml?type=student_view"));
nameValuePairs.add(new BasicNameValuePair("currDomain",
"beardenhs.knoxschools.org"));
nameValuePairs.add(new BasicNameValuePair("username", username
.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", password
.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String g = httppost.getURI().toString();
HttpResponse response = httpclient.execute(httppost);
HTML = EntityUtils.toString(response.getEntity());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String ResponseBody = httpclient.execute(httppost, responseHandler);
sting.setText(HTML);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
When a server sends a redirect, it is actually sending a 3xx response code (usually 301 or 302) that indicates the redirect, and a Location header that tells you the new location.
So, in your case, you can get the Location header from the HttpResponse object and use that to send another request to retrieve the actual content after you've logged in. For example:
String newUrl = response.getFirstHeader("Location").getValue();
So long as you reuse the same HttpClient object for both requests, it should use any cookies set by the login request in your subsequent request(s).
Try using the HttpGet method
GetMethods will follow redirect requests from the http server by default. This behavour can be disabled by calling setFollowRedirects(false).
For more info refer this
Hope it helps,
Cheers

Android post request

I have javascript code that i am trying to mimic in an android application:
Here is the javascript code:
text = '{"username":"Hello","password":"World"}';
x.open("POST", url);
x.setRequestHeader("Content-type", "application/json");
x.setRequestHeader("Content-length", text.length);
x.send(text);
and here is what i have so far for the android application(doesnt work):
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-type", "application/json");
String text = "\"{\"username\":\"Hello\",\"password\":\"World\"}\"";
httppost.setHeader("Content-length",Integer.toString(text.length()));
httppost.setEntity(new StringEntity(text));
HttpResponse response = httpclient.execute(httppost);
when i try to debug this code on eclipse the emulater keeps running while the debugger hangs. Thanks!
Note: its hanging on httpclient.execute(httppost)
Here is the code I use for Android post requests:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("fullurl");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("parameter", "variable");
post.setEntity (new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
...and so on.
Try it out:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
JSONObject json = new JSONObject();
try{
json.put("username", "Hello");
json.put("password", "World");
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
catch(Exception e){
e.printStackTrace();
}
Did you mean to set your HttpPost path to just path. I think your hanging because you haven't given the HttpPost a valid URL. You'll need to modify this line:
HttpPost httppost = new HttpPost("path");
to something like
HttpPost httppost = new HttpPost("actual/url/path");
You have extra speech marks within the start and end of your text string compared to the JS version?
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(StringUrl);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
System.out.println("rep => " + response);
} catch (IOException e) {
System.out.println(e);
}
}

apache httppost how to set content : which have name value pair pointing to another set of name value pair

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");
}
}

How do I pass a JSONObject to a PHP file?

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.

Categories

Resources