Good day.Im sending post request to php server side like this
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("my server name");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
/*StringTokenizer tokens = new StringTokenizer(from.getText().toString(), "-");
String shortstring = tokens.nextToken();
String longstring = tokens.nextToken();
StringTokenizer tokens2 = new StringTokenizer(to.getText().toString(), "-");
String shortstringto = tokens2.nextToken();
String longstringto = tokens2.nextToken();*/
try {
reqEntity.addPart("type", new StringBody("3"));
Server side receives it like this
Array
(
[type] => 3
)
All seems good which afar he wants me to send to him an array.I do send it like this
ArrayList<String> array = new ArrayList();
aray.add("hello");
reqEntity.addPart("array", new StringBody(array.toString()));
he receives it like this
Array
(
[type] => 1
[array]=> [hello];
)
All seems good but he assumes thats I'm sending wrong and he wants the array to be send so he can receive it like this way.
Array
(
[type] => 1
[array]=> Array(
[header name of my array]=>"value of array"
)
)
I google every bit i read every single line of every site,and did not found anything even close to what he wants as if i send array it will be like i wrote,otherwise he just wants array of inside another array with KEY name of inner array and with VALUE of inner array,which i don't know but somehow not possible for my opinion in the way he wants.So is it possible?can i send array the way he wants in my last written code?
Sorry don't have enough points to post a comment. But you need to provide a little more information about which server you are using.
If you are using PHP, it is pretty much simple, once you have set up a secure connection you just need to send the response in the following manner:
$response["success"] = 0;
$response["message"] = "Some Message";
die(json_encode($response));
JSONObject jsonObject =new JSONObject();
JSONArray taskDoneJsonArray= new JSONArray();
taskDoneJsonArray.add("aa");
JSONArray nextStepsJsonArray= new JSONArray();
nextStepsJsonArray.add("bb");
try {
jsonObject.put("accessToken", "something");
jsonObject.put("taskDone",taskDoneJsonArray);
jsonObject.put("nextTask",nextStepsJsonArray);
jsonObject.put("issueRemaining",issuesQueriesJsonArray);
}
catch (JSONException jsonException){
ToastMessage.show(context,context.getResources().getString(
R.string.error)+jsonException.getMessage());
}
Now use jsonObject
Related
I am attempting to add some Book(title, author, year) into my book table in a server using an AsyncTask, but i am getting missing bookobject as JSONfrom the method addBook(from the server). So i made a bookObject like this:
JSONObject jObj = new JSONObject();
jObj.put("title", "JAVA");
jObj.put("author", "me");
jObj.put("year", 2005);
After that, i wanna use(my intention is to send this book Object):
List<NameValuePair> nameValuePairs = new ArrayList<>(1);
nameValuePairs.add(new BasicNameValuePair(jObj)); //Error
new AaaBookAsyncTask(this).execute(new Pair<>(nameValuePairs, httpClient));
The problem is BasicNameValuePaircannot applied to JSONObject, but now how can i send the book Object? - Any help or hints is very appreciated.Thanks, Carl
You could send the JSON as a string and then decode it on your server before storing it in your database.
I'm trying to figure out what the best method to send two strings and an integer to a server. Should I use a database? I want to achieve a queue effect and not really store the data online for too long. I just want to grab the information in the queue with a different program. The android would just need to send the data to the web server, but I'm not sure what kind of data structures I should be researching.
So I'm really looking for ideas of some kind of scripts I can be running on a web-server and how to implement sending to them via android. I don't need specific code, but an idea I could research would work too. I really appreciate any help.
Simple, Encode what you need to send in JSON and send it. I'll quote an example below, I have a server running Django and have set up an API to save the data into the database when I hit the url with a post request. I send the Location (latitude and longitude) along with the current datetime. On my server a view runs and parses the json and then saves it to DB.
In your case however you can just manipulate the data the way you want and not save it.
try
{
double la = 30.1955600 ;
double lo = 71.4752800;
Time t = new Time(Time.getCurrentTimezone());
t.setToNow();
String date = t.format("%Y-%m-%d %H:%M:%S");
JSONObject o1 = null;
o1 = new JSONObject();
o1.put("latitude", loc.latitude);
o1.put("longitude", loc.longitude);
o1.put("date_added", date);
// http call//
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost("the url you want to hit");
StringEntity _params =new StringEntity(o1.toString());
request.addHeader("content-type", "application/json");
request.setEntity(_params);
HttpResponse response = httpClient.execute(request);
//check to see if we got a response
if (response.getEntity() != null)
HomeScreen.location_sent = true;
else
HomeScreen.location_sent = false;
}
catch (Exception e)
{
e.getMessage();
}
It has been a while since I programmed for Android and I have lost all my previous work which had the code in it I am having problems with. I am developing an app for both Android and iPhone which connect to the same server to download data. All is well in the iPhone version but on Android when I hit the server with the post data containing the method name I would like to to run on the server it seems that the data is not added to the request.
Why is the POST not working in this request for Android but does for the iPhone version of the app?
Here is the code I am using:
public static void makeRequest() throws Exception {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
HttpEntity entity;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost("http://divisi.co.uk/rest/requesthandler.php");
json.put("method", "getEventListData");
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
entity = response.getEntity();
String retSrc = EntityUtils.toString(entity);
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
if(result.getString("SC") == "200"){
JSONArray data = result.getJSONArray("data");
}
else{
}
} catch(Exception e) {
e.printStackTrace();
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
The response I get mack from the server is:
{"data":{"scalar":""},"SC":405,"timestamp":1363788265}
Meaning the method name was not found, i.e. not posted in my request to the server.
heres an example of how i do things like this:
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://divisi.co.uk/rest/requesthandler.php");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart(new FormBodyPart("method", new StringBody("getEventListData")));
reqEntity.addPart(new FormBodyPart("NEED_A_KEY_HERE", new StringBody("" + json.toString())));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
JSONObject responseDict = new JSONObject(EntityUtils.toString(response.getEntity()));
allow this is your "http://divisi.co.uk/rest/requesthandler.php" page code, then in android you can use this... you don't allow post in your URL,
use fiddler on your sever side. see if the http message is correct. it seems your sever side problem, can you show us your sever side code which receive and parse json.
If the server can't read your request try to remove:
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
It will use the mime type defaults HTTP.PLAIN_TEXT_TYPE i.e. "text/plain".
I don't see any other possibility, if your code is the one you posted and not a more complicated input JSON object.
Your code to set the POST body may be just fine. I think the problem may be with your web service. Try using something like Rested or curl to manually make the call to your server. I made exactly the same request you are making, including with and without the POST body, and I got the same response from your server:
{"data":{"scalar":""},"SC":405,"timestamp":1365704082}
Some things that may be tripping you up:
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
if(result.getString("SC") == "200"){
JSONArray data = result.getJSONArray("data");
}
Here, you are comparing the string "405" to "200" using ==, when you should first do a null check and then use .equals("200") instead. Or, use result.getInt("SC") == 200 since this is an integer type in your response JSON.
Also, the "data" entity from your server response is not actually coming back as a JSON array. You should use getJSONObject("data") instead.
Additionally, it's always a good idea to externalize your strings.
Here's how the code should look:
public static final String JSON_KEY_SC = "SC";
public static final String JSON_KEY_DATA = "data";
...
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
String sc = result.getString(JSON_KEY_SC);
if (sc != null && sc.equals("200")) {
JSONObject data = result.getJSONObject(JSON_KEY_DATA);
}
else {
...
}
I have a android application which sends JSON information to a webservice for it to validate the information. I am using Kate as an editor for the webservice. The concept of JSON and php webservices is new to me. I normally code in java.
JSONObject jsonObject = new JSONObject();
String userID = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(loginURI);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams,10000);
try {
jsonObject.put("username", username);
Log.i("username", jsonObject.toString());
jsonObject.put("password", password);
Log.i("password", jsonObject.toString());
StringEntity stringEntity = new StringEntity(jsonObject.toString());
stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
userID = EntityUtils.toString(httpResponse.getEntity());
Log.i("Read from server", userID);
}
}catch (IOException e){
Log.e("Login_Issue", e.toString());
}catch (JSONException e) {
e.printStackTrace();
}
return userID;
}
I found the StringEntity code online and thought it will work. I do not understand the purpose of the StringEntity for the HttpPost.
This is my webservice written in php.
include('dbconnect.php');
$tablename = 'users';
//username and password sent from android
$username=$_POST['myusername'];
$password=$_POST['mypassword'];
//protecting mysql injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
#$array = array($username,$password);
$sql = "SELECT first_name FROM $tablename WHERE u_username='$username' AND u_password=MD5('$password')";
//Querying the database
$result=mysql_query($sql);
if(!$result){
die(mysql_error();
}
//If found, number of rows must be 1
if((mysql_num_rows($result))==1){
//creating session
session_register("$username");
session_register("$password");
print true;
}else{
print false;
}
mysql_close();
I am not quite sure if the 'username' and the 'password' is being sent correctly from the android app to the webservice. How can I verify this? And is the webservice and the java code well-written to send the information in JSON?
When I go the webservice on the browser, I get the following error:
Parse error: parse error in E:\wamp\www\mobile.dcl.mu\webserver\login.php on line 24
Thank you in advance.
You try to bite off too much. It should be, like, 6 different questions (or just pay someone to write the scripts for you, or spend some time learning the technologies in isolation). Two first things to fix:
fix the parse error! it is as if you had a Java source that does not compile. The error is that you forgot the closing paren after die (mysql_error();
no, it will not work anyway. You send the data in the body as application/json, and you try to read it as url-encoded form. Decide which you want, ask for help on that.
remove the stripslashes. It does not add any security and will cause errors if anyone is using a slash in her password. Unless you have magic_quotes on, which you should not.
Since you made the three very basic mistakes so early, I am practically sure that there is much, much more to fix. Other than rewriting the whole thing for you or sending some general links on PHP programming and web application programming - I see no more way to help you. If you manage to split the problem, test things in isolation and ask more questions, there might be hope.
UPDATE
If you decide to standardize around JSON, the general pattern in your PHP files will be:
// get the body of the HTTP request (that's the "http entity")
$body = file_get_contents('php://input');
// translate JSON into ordinary PHP array:
$entity = json_decode($test, true);
// Now you can read parts of it as if you read an array;
// the data may be nested and will mirror exactly your JSONObject:
$username=$entity['myusername'];
$password=$entity['mypassword'];
[yes, that's me begging for an upvote :-)]
[and I think there is more problems in your Java code, but one thing at a time]
I've been looking online for how to pass parameters to RESTlet webservice but it seem there are not much tutorial concerning RESTlet.
I would like to send some parameters gathered from a form on my android application (it would be great if i could do this using JSON).
well i solved this
as for the server side
#Post
public JSONArray serverSideFunction(Representation entity)
throws JSONException {
try {
JSONObject req = (new JsonRepresentation(entity)).getJsonObject();
System.out.println(req.getString(/* filed name */));
System.out.println(req.getString(/* filed name */));
/*
* you can retrieve all the fields here
* and make all necessary actions
*/
} catch (IOException e) {
e.printStackTrace();
}
}
as for the Android Side
HttpClient client = new DefaultHttpClient();
String responseBody;
JSONObject jsonObject = new JSONObject();
try{
HttpPost post = new HttpPost(WebService_URL);
jsonObject.put("field1", ".........");
jsonObject.put("field2", ".........");
StringEntity se = new StringEntity(jsonObject.toString());
post.setEntity(se);
post.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setHeader("Content-type", "application/json");
Log.e("webservice request","executing");
ResponseHandler responseHandler = new BasicResponseHandler();
responseBody = client.execute(post, responseHandler);
/*
* You can work here on your responseBody
* if it's a simple String or XML/JSON response
*/
}
catch (Exception e) {
e.printStackTrace();
}
I hope this may be of help
In fact, it depends on what you want to do. With REST (see http://en.wikipedia.org/wiki/Representational_state_transfer), there are two ways to pass parameters or data. Before you need to understand some concepts:
Resource: the REST entity by itself.
Representation: corresponds to its state and can be gotten or updated using different HTTP methods. The kind of content is identified using the content type header (media type in Restlet).
Methods: the GET method is used to get the resource state, PUT to update it, POST to create a new resource and specify its state the same time, DELETE to delete a resource.
Restlet provides Java entities for REST elements.
So, after described that, you can see that passing data or parameters depends of your use case:
1°) Do you want to update the resource state? In this case, you will use the content of the request with methods like POST or PUT. The data structure is free from text, JSON, XML or binary... Restlet provides the ClientResource class to execute requests on RESTful applications. It also provides support to build the representation to send and extract data from the one received. In this case, your data gathered from a form will be used to build the representation. Here are some samples:
//Samples for POST / PUT
ClientResource cr = new ClientResource("http://...");
cr.post(new StringRepresentation("test"));
MyBean bean = new MyBean();
(...)
//Jackson is a tool for JSON format
JacksonRepresentation<MyBean> repr
= new JacksonRepresentation<MyBean>(bean);
cr.put(repr);
//Samples for GET
Representation repr1 = cr.get();
bean = (new JacksonRepresentation<MyBean>(repr1, MyBean.class)).getObject();
2°) Do you want to specify parameters on your GET requests (for example to configure data to retreive and so on)? In this case, you can simply add it on the ClientResource, as described below:
ClientResource cr = new ClientResource("http://...");
cr.getReference().addQueryParameter("q", "restlet");
Representation repr = cr.get();
In this case, your data gathered from a form will be used to build the parameters.
Hope it helps you.
Thierry
If you want request with json structure and your response as JSONObject maybe you can do like this in server side:
public class RequestJSON extends ServerRecource{
#Post("json")
public JSONObject testRequest(String entity){
JSONObject request = new JSONObject(entity);
String value1 = request.getString("key1");
int value2 = request.getInt("key2");
return /* your JSONObject response */;
}
}
And your request can be :
{"key1":"value1", "key2":value2}
I hope this can help you