Calling Rest webservice in Android - android

I have Java web application server [ acts like server ].
In Android application, using httppost i have calling the restwebserive server.
My calling is hit the webservice with the response code 200.
Now i want to pass the java class object as like parameter.
sample java class:
public Class Sample{
public String Username;
public String getUsername()
{
return Username;
}
public void setUsername(String user){
this.Username = user;
}}
Used code :[ Is not passing my class object to server ]
Sample sam = new Sample();
sam.setUsername("Test");
JSONObject json = new JSONObject();
json.put("Sample", sam);
StringEntity se = new StringEntity(json.toString());
Httppostrequest.setEntity(se);
when i debugging the server the sample object parameter input is empty.[Not passed properly]
How to pass the class object via http post in android?
Please help me on this.
Thanks in advance,
Kums

if you use apache library you can do it one line
JSONSerializer.toJSON(sam);
otherwise i think you have to send it as
Sample sam = new Sample();
sam.setUsername("Test");
JSONObject json = new JSONObject();
json.put("sample", sam.getUserName());
StringEntity se = new StringEntity(json.toString());
Httppostrequest.setEntity(se);

Here is a code snippet
public void callWebService(String q){
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(URL + q);
request.addHeader("deviceId", deviceId);
ResponseHandler<string> handler = new BasicResponseHandler();
try {
result = httpclient.execute(request, handler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
Log.i(tag, result);
} // end callWebService()
}
Use this method to call your webservice

I have built a library for doing async requests, you can send parameter requests as www.somedomain.com/action?param1="somevalue" etc.. and also there is the option to use string body.
https://github.com/darko1002001/android-rest-client
Check it out, it might be helpful.

Related

Recieving HTML file as responce instead of JSON Object through get request

I am developing an android app where user logs on to his/her account. After logging in I will receive XSRF token and Laravel Session Id to recognise the specific user. I have to send these tokens for every request I send to the API's to get the appropriate information. But when I am sending the required details as shown in the image, I am getting HTMl file as response instead of getting JSON Object. I was seriously stuck at this problem. Correct Solution may take forward the whole app.
class RegisterConnection extends AsyncTask<String,String,JSONObject> {
protected JSONObject doInBackground(String... arg0) {
JSONObject output = new JSONObject();
DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 5000); //Timeout Limit
HttpResponse response = null;
try {
HttpGet get = new HttpGet(statsURL);
get.setHeader("Accept", "application/json");
CookieStore store = new BasicCookieStore();
BasicClientCookie cookie1 = new BasicClientCookie("XSRF-TOKEN", XSRF);
BasicClientCookie cookie2 = new BasicClientCookie("laravel_session", laravel);
store.addCookie(cookie1);
store.addCookie(cookie2);
client.setCookieStore(store);
response = client.execute(get);
if(response!=null){
InputStream in = response.getEntity().getContent();
String resultstring = Utilities.convertStreamToString(in);
Log.i("Result1", resultstring);
output = new JSONObject(resultstring);
Log.i("Result2", output.toString());
}
} catch(Exception e) {
e.printStackTrace();
try {
output.put("sai","error");
Log.i("MainActivity", output.toString());
} catch (JSONException e1) {
e1.printStackTrace();
}
return output;
}
return output;
}
These are the server requirements
http://imgur.com/OY9Q673
This is the Output received
http://imgur.com/IB5AEcT
As far as I can tell, there is nothing wrong with your Android client code.
You are getting HTML from the server so the main reason could be that your Laravel server is rendering the views and sending you back html instead of JSON. Instead of rendering the views on the server, you should send JSON response on your Laravel server side.
Add Jsoup dependency in your gradle file
implementation 'org.jsoup:jsoup:1.11.2'
Document document = Jsoup.parse("http://imgur.com/IB5AEcT");
Elements el = doc.select("button");
Log.i("..........",""+el.attr("data-invite-details"));
Jsoup tutorial
http://jsoup.org/apidocs/org/jsoup/Jsoup.html

Send JSON in Post with robospice google http client

I have a problem with creating post requests and send json with Robospice google http java client. My problem is, that the server receives an empty request data. (Nothing in postData)
#Override
public AjaxResult loadDataFromNetwork() throws Exception {
JsonHttpContent jsonHttpContent = new JsonHttpContent(new JacksonFactory(), jsonObject);
//ByteArrayContent.fromString("application/json", jsonObject.toString())
HttpRequest request = getHttpRequestFactory().buildPostRequest(
new GenericUrl(baseUrl),
jsonHttpContent);
request.getHeaders().setContentType("application/json");
request.setParser(new JacksonFactory().createJsonObjectParser());
request.setContent(jsonHttpContent);
HttpResponse httpResponse = request.execute();
AjaxResult result = httpResponse.parseAs(getResultType());
return result;
}
Thanks in advance!
You can do something like this :
public class SignIn_Request extends GoogleHttpClientSpiceRequest<Login> {
private String apiUrl;
private JSONObject mJsonObject;
public SignIn_Request(JSONObject mJsonObject) {
super(Login.class);
this.apiUrl = AppConstants.GLOBAL_API_BASE_ADDRESS + AppConstants.API_SIGN_IN;
this.mJsonObject = mJsonObject;
}
#Override
public Login loadDataFromNetwork() throws IOException {
Ln.d("Call web service " + apiUrl);
HttpRequest request = getHttpRequestFactory()//
.buildPostRequest(new GenericUrl(apiUrl), ByteArrayContent.fromString("application/json", mJsonObject.toString()));
request.setParser(new JacksonFactory().createJsonObjectParser());
return request.execute().parseAs(getResultType());
}
}
Convert your JSON into byte array and include it in your post request.
I've been hunting around for a similar solution myself and I found a decent explanation of how Google want you to format the content.
I made POJO class and just added some getters and setters and used that for the data and it seemed to work for me.
google-http-java-client json update existing object

List of user-defined objects from Android to an ASP.NET webservice through JSON

I have a web service written in ASP.NET that accepts a List of type Contact(List).
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
#region List of contacts that need to be created in the database.
public List<KeyValue> createRecordsInDb(List<Contact> dataToPass)
{
return Contact.insertArrayIntoDb(dataToPass);
}
#endregion
On the android device, I am converting a List to a String using the GSON library.
List<Contact> lstContactsToCreate= retrieveDataFromCursor(cursor,false);
String jsonString = new Gson().toJson(lstContactsToCreate);
try {
callWebService(jsonString, _context.getResources().getString(R.string.updateCreateURL), false);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The problem arises when I wish to send the data to the web-service. I'm passing the data through the following method,
private HttpResponse callWebService(String dataToPass, String URL, boolean isUpdate)
throws JSONException, ClientProtocolException, IOException{
HttpPost httpPost = new HttpPost(URL);
httpPost.setHeader("content-type", "application/json");
HttpClient httpClient = new DefaultHttpClient(getHttpParameterObj(4000,4000));
// Building the JSON object.
JSONObject data = new JSONObject();
data.put("dataToPass", dataToPass);
StringEntity entity = new StringEntity(data.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
entity.setContentEncoding( "UTF-8");
httpPost.setEntity(entity);
// Making the call.
HttpResponse response = httpClient.execute(httpPost);
return response;
}
Whenever I call the webservice, it throws the following error -
{"Message":"Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.List`1
The problem is that data.toString() returns :-
{"dataToPass":"[{\"address\":\"Himayath Nagar\",\"email\":\"abijeet.p#osmosys.asia\",\"name\":\"Abijeet Patro\",\"server_id\":\"\",\"status\":\"\"},{\"address\":\"himayath naga\",\"email\":\"saravana.e#osmosys.asia\",\"name\":\"Saravana\",\"server_id\":\"\",\"status\":\"\"},{\"address\":\"hellpo world\",\"email\":\"asshole#gmail.com\",\"name\":\"Syai\",\"server_id\":\"\",\"status\":\"\"}]"}
whereas the webservice expects data in the format
{"dataToPass":[{\"address\":\"Himayath Nagar\",\"email\":\"abijeet.p#osmosys.asia\",\"name\":\"Abijeet Patro\",\"server_id\":\"\",\"status\":\"\"},{\"address\":\"himayath naga\",\"email\":\"saravana.e#osmosys.asia\",\"name\":\"Saravana\",\"server_id\":\"\",\"status\":\"\"},{\"address\":\"hellpo world\",\"email\":\"asshole#gmail.com\",\"name\":\"Syai\",\"server_id\":\"\",\"status\":\"\"}]}
I even tried replacing and removing those " " as such :-
data.toString().replace("\"[","[").replace("]\"","]");
(java.lang.String) {"dataToPass":[{\"address\":\"Himayath Nagar\",\"email\":\"abijeet.p#osmosys.asia\",\"name\":\"Abijeet Patro\",\"server_id\":\"\",\"status\":\"\"},{\"address\":\"himayath naga\",\"email\":\"saravana.e#osmosys.asia\",\"name\":\"Saravana\",\"server_id\":\"\",\"status\":\"\"},{\"address\":\"hellpo world\",\"email\":\"asshole#gmail.com\",\"name\":\"Syai\",\"server_id\":\"\",\"status\":\"\"}]}
But that does not seem to be working as the Web Server throws an error
{"Message":"Invalid object passed in, member name expected. (16): {\"dataToPass\":[{\\\"address\\\":\\\"Himayath Nagar\\\",\\\"email\\\":\\\"abijeet.p#osmosys.asia\\\",\\\"name\\\":\\\"Abijeet Patro\\\",\\\"server_id\\\":\\\"\\\",\\\"status\\\":\\\"\\\"},{\\\"address\\\":\\\"himayath naga\\\",\\\"email\\\":\\\"saravana.e#osmosys.asia\\\",\\\"name\\\":\\\"Saravana\\\",\\\"server_id\\\":\\\"\\\",\\\"status\\\":\\\"\\\"},{\\\"address\\\":\\\"hellpo world\\\",\\\"email\\\":\\\"asshole#gmail.com\\\",\\\"name\\\":\\\"Syai\\\",\\\"server_id\\\":\\\"\\\",\\\"status\\\":\\\"\\\"}]}","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeList(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
So how do I pass an array of user-defined objects from Java to my ASP.NET web service? Or is there way I can convert the GSON string on the asp.net web server to my List objects?
Can I use JSON.NET to de-serialize the string to my List?
This link has an answer that worked. I am just getting the data on the server side as string, and then converting it the array that I can process.
Sample JSON:
string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]";
Class:
public class Person
{
public int Age {get;set;}
public string Name {get;set;}
}
Deserialization
JavaScriptSerializer js = new JavaScriptSerializer();
Person [] persons = js.Deserialize<Person[]>(json);
May not be the best answer, since we may not always have access to the code of the Web Server. I'll be leaving this open for a while longer.

Trouble sending JSON Post Android

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 {
...
}

How do I invoke a servlet from my android application?

I am absolutely new to android development and I need help in know how can I invoke a remote servlet which is gonna send me data from a database in the form of xml. I am a beginner and I don't understand jargon. If possible provide me with a link/tutorial for the same.
Any help is greatly appreciated, Thanks!
you need to do this while making a get request.
public boolean funtionAtSite(String sentUrl) {
String url = sentUrl;
HttpGet getMethod = new HttpGet(url);
DefaultHttpClient client = new DefaultHttpClient();
try {
ResponseHandler<String> reponseHandler = new BasicResponseHandler();
String responseBody = client.execute(getMethod, reponseHandler);
/******** now do what you want to do with response **********/
if (responseBody.equalsIgnoreCase("1")) {
Log.v(TAG, responseBody);
return true;
}
return false;
} catch (Throwable t) {
return false;
}
}

Categories

Resources