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.
Related
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);
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;
?>
here is my java code and it makes an http request and send json object to php script.
login.java
String username = jTextField1.getText();
String password = jPasswordField1.getText();
JSONObject obj = new JSONObject();
obj.put("username", username);
obj.put("password", password);
//JSONArray list = new JSONArray();
//list.add(username);
//list.add(password);
//obj.put("logindata", list);
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
HttpPost httppost = new HttpPost("http://localhost/kolitha/json_test/index.php");
StringEntity se = new StringEntity("myjson" + obj.toString());
httppost.setEntity(se);
System.out.print(se);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
System.out.println(obj.toString());
//response = httpclient.execute(httppost);
HttpGet httpget = new HttpGet("http://localhost/kolitha/json_test/index.php");
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity));
} catch (Exception e) {
e.printStackTrace();
System.out.print("Cannot establish connection!");
}
this is my index.php script and i am unable to extract username and password from the json object.
index.php
$obj = json_decode(file_get_contents('php://input'));
$username=$obj->{'username'};
$password=$obj->{'password'};
$connect=mysql_connect('localhost', 'root', '');
IF (!$connect){
die ('Failed Connecting to Database: ' . mysql_error());}
$d = mysql_select_db("kolitha_json_test");
if(!$d){ echo "db not selected";}
$sql="SELECT * FROM login WHERE username='$username' AND password='$password' ";
$result=mysql_query($sql) or die (mysql_error());
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
echo "true";
}
else
{
echo "false";
}
?>
Ok i left a comment but no one seems to pay attention to a comment. The error is in the Java Code
StringEntity se = new StringEntity("myjson" + obj.toString());
which adds a prefix to the json string called myjson
Why are Using both HttpPost and HttpGet. You are adding string entity to HttpPost request and not using it..
whereas you are using Httpget where you have not set ur username and password(so obviously there is no json data associated with httpget request)
Make changes here
response = httpclient.execute(httppost);//don comment this line
Add comment hereif you are using httppost
//HttpGet httpget = new HttpGet("http://localhost/kolitha/json_test/index.php");
//response = httpclient.execute(httpget);
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);
}
}
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");
}
}