As of now, if I have to store something from Android to the server, I make an HTTP request of a GET URL, with data in the form of parameter values. On the server side, I use PHP to extract the parameter values and store them in database.
Similarly, if I want to get something from the server to Android, I post a JSON string on the webpage using PHP. Then I read it in Android using HTTP request, convert the string to JSON and then use the data.
This method of PHP-MySQL-Android-JSON is very easy but not secure. Suppose I want to store the score of player from my game in Android to the server's database, it is easy to execute some URL like www.example.com/save_score.php?player_id=123&score=999 from Android. But anyone can update his score if he comes to know the php file name and names of parameters, by simply typing this URL in a browser.
So what is the correct method of interacting with a server (my server supports PHP but not Java)?
I have heard about RESTful and KSOAP2, but know nothing about them. Can you please explain them a bit in lay man language (reading the proper definitions didn't help me)? What are these used for?
What is the best way to send score to the server? Any tutorial link would be great.
Thanks.
Edit 1:
I don't use proguard to obfuscate my code for several reasons. So anyone can reverse engineer the apk, look into the code, find the URL to update the score, write his own POST method and update his score. How can I stop this from happening?
Use POST method to post data from android and get it in php. e.g. use this method to send your data in json formate , which will not be showing in url.
public static String sendRequest(String value, String urlString) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlString);
httppost.setHeader( "Content-Type", "application/json");
//value = "";
StringEntity stringEntity = new StringEntity(value);
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
httppost.setEntity(stringEntity);
HttpResponse response = httpclient.execute(httppost);
String responseString = convertStreamToString(response.getEntity().getContent());
return responseString;
} catch (Exception e) {
Log.d("check", ""+e.getMessage());
return ERROR_SERVICE_NOT_RESPONDE;
}
}
And call this method like this.
sendRequest({"player_id":1,"score":123}, "www.example.com/save_score.php");
And get json body in php and parse it.
I think you should read more documents about RESTful, Http POST and GET before starting. Your example url is GET method. It should be used for getting public information or query data. If you want to change something in server side, you should use POST method, it is more security than GET.
My recommend is using RESTful because it is painless than SOAP, especially for Android. Here is an example HTTP POST on Android.
Related
I have HTTP path that need to send JSON
{
"domain": "mas.org.il",
"params": {
"type":"hug"
}
}
to get another JSON with all items to insert into my Android app
How do I send this JSON to http URL and get JSON to parse it into my app.
please read this useful document to know how can you implementing this feature
https://www.itsalif.info/content/android-volley-tutorial-http-get-post-put
Just to give a vary basic idea,add the json in apache NameValue pair or use apache Entitys with HttpPost .. or you can follow this.
How To Send json Object to the server from my android app
someone may asked my question already but I cannot find any suggestions.
I writing an Android app which needs to access my Django server by using HttpsURLConnection then Django server will return a JSON array to Android.
The view function in Django will receive the parameters from request.POST and generate the JSON array then return using HTTPResponse Django method. It does not need any Templates and Forms.
When I call the Django view function from Android, it returns 403 error. I know that it is because the POST data does not contains "csrf_token".
My problem is: How can I get the "csrf_token" and put it into my POST data before I send it to Django? I try disable the CSRF checking by "#csrf_exempt" it can return the correct result to Android app but I would not disable the CSRF checking.
Thanks,
Wilson
You have to send the cookies and also have to send a header 'X-CSRFToken' with csrftoken.
This is what I do (may not be the best way):
Get csrf token via a get request.But first try to see if you get a csrftoken cookie by doing same request on your browser with developer tools. If not, you should use ensure_csrf_cookie decorator
from django.views.decorators.csrf import ensure_csrf_cookie
#ensure_csrf_cookie
def your_view(request):
pass
Now using the same HttpUrlConnection object do this :
String cookieString="";
String csrftoken="";
// The below code can be shortened using for-each loop
List<HttpCookie> cookies=cookieManager.getCookieStore().getCookies();
Iterator<HttpCookie> cookieIterator=cookies.iterator();
while(cookieIterator.hasNext()){
HttpCookie cookie=cookieIterator.next();
cookieString+=cookie.getName()+"="+cookie.getValue()+";";
if(cookie.getName().equals("csrftoken")){
csrftoken=cookie.getValue();
}
}
Add the following to your post request:
urlConnection.setRequestProperty("X-CSRFToken", csrftoken);
urlConnection.setRequestProperty("Cookie", cookieString);
i am new to WCF
i have created WCF which retrieve data from database and this will execute thru asp.net application
now, i want to use this WCF in my android application
can anybody tell me what should i do ?
i have study but i got little hint, about SOAP and REST.
so which would be preferable for me ? can anybody give me hint or code ?
i need ready working code snippet
URI uri = null;
try {
uri = new URI("http://localhost:3997/AWS_WCF_Service.svc");
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpGet httpget = new HttpGet(uri + "/SayHello");
httpget.setHeader("Accept", "application/json");
httpget.setHeader("Content-type", "application/json; charset=utf-8");
HttpResponse response = null;
response = httpClient.execute(httpget);
Thank YOu
Exactly how might depend on which version of ASP.Net you're using, but you will need your Web app to expose your WCF objects using a service. If you are using 4.0, either SOAP or REST services are options (Web Service or WebAPI service). If you want a philosophical debate about their respective merits, this might be a place to start: SOAP or REST for Web Services?, but since both can return JSON, either is probably fine for your Android app.
I have .Net 3.5 myself so I've mostly been using the Web Service version (with an .asmx file), and found the following link immensely useful:
Android -- How to access data in an ASP.NET database via app?
The accepted answer on that thread got me set up with a basic Web Service and little Android app in one afternoon! (This was admittedly with me having some little knowledge of both)
If you want a RESTful service and you have .Net 4.0, I suspect you could achieve your aim by following a tutorial on the subject (like this one http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api), and then using the Android code from the link above.
(Something worth bearing in mind when working with ASP.Net services returning JSON is that the returned object will be wrapped in an object called "d" - see Why do ASP.NET JSON web services return the result in 'd'?. I haven't used XML so I don't know if there are any issues for that format.)
I'm writing an Android app that should get data from a certain web application. That web app is based on Servlets and JSP, and it's not mine; it's a public library's service. What is the most elegant way of getting this data?
I tried writing my own Servlet to handle requests and responses, but I can't get it to work. Servlet forwarding cannot be done, due to different contexts, and redirection doesn't work either, since it's a POST method... I mean, sure, I can write my own form that access the library's servlet easily enough, but the result is a jsp page.. Can I turn that page into a string or something? Somehow I don't think I can.. I'm stuck.
Can I do this in some other way? With php or whatever? Or maybe get that jsp page on my web server, and then somehow extract data from it (with jQuery maybe?) and send it to Android? I really don't want to display that jsp page in a browser to my users, I would like to take that data and create my own objects with it..
Just send a HTTP request programmatically. You can use Android's builtin HttpClient API for this. Or, a bit more low level, the Java's java.net.URLConnection (see also Using java.net.URLConnection to fire and handle HTTP requests). Both are capable of sending GET/POST requests and retrieving the response back as an InputStream, byte[] or String.
At most simplest, you can perform a GET as follows:
InputStream responseBody = new URL("http://example.com").openStream();
// ...
A POST is easier to be performed with HttpClient:
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("name1", "value1"));
params.add(new BasicNameValuePair("name2", "value2"));
HttpPost post = new HttpPost("http://example.com");
post.setEntity(new UrlEncodedFormEntity(params));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
InputStream responseBody = response.getEntity().getContent();
// ...
If you need to parse the response as HTML (I'd however wonder if that "public library service" (is it really public?) doesn't really offer XML or JSON services which are way much easier to parse), Jsoup may be a life saver as to traversing and manipulating HTML the jQuery way. It also supports sending POST requests by the way, only not as fine grained as with HttpClient.
I've a application deployed on google app-engine..it has a registration form.
now i've made a registration form in my android application and i want that on click submit...it should be sent to the application on google app-engine and it should be persisted in the particular db...
somebody told me to use http request and response method but i'm not aware of that thing..
can somebody please provide me with some sample code or something.....
thanksss....
You haven't specified if you're using Python or Java.
You have to decide how you want to connect. At the simplest level you could just POST the data to Google App Engine. In Java you would write a servlet which handles this. See Java EE tutorial. Alternatively you could write a web service (SOAP, RESTful) on the server which handles the data being sent from your application. Again Google this and there are countless examples.
Assume we're going down the simplest POST route. So in your servlet (running on GAE) you'd have something like this:
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String value1 = request.getParameter("value1");
}
And in your android app you'd do something like:
DefaultHttpClient hc=new DefaultHttpClient();
ResponseHandler <String> res=new BasicResponseHandler();
HttpPost postMethod=new HttpPost("http://mywebsite.com/mappedurl");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("value1", "Value my user entered"));
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String response=hc.execute(postMethod,res);
Of course value1 in the servlet would be set to "Value my user entered".
EDIT: Google have now released their Google Cloud Endpoints - this makes building RESTful services on App Engine and creating clients for Android a lot easier. It does tie you in to App Engine even more though - but certainly worthy of consideration.