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.)
Related
I am testing an Android app which is connected to my local router. On the same WiFi network are also running some Java web services using Restlets. I verified that the Android app can hit the service filter and even receive a response from the service filter. However, it cannot seem to hit the Restlet service in question.
The full URL to the service is:
http://192.168.0.148:8080/MyApp/service/login
where 192.168.0.148 is the local IP address of the computer running the Restlet web services.
I have the service mapped in my Restlet Application class as follows:
router.attach("/login", LoginResource.class);
My web.xml file has the appropriate mappings to route anything with the pattern /service/ to the Restlet servlet.
I can successfully hit this service when testing from SOAP UI using precisely the same URL I gave above. In fact, all web services have been tested end-to-end using SOAP UI and are completely functional.
For some reason, the Android app can hit the service filter, when but when it reaches:
chain.doFilter(request, response);
the request ends up lost in space, and nothing gets returned.
I suspect that this is largely a Reslets configuration problem, though I don't know exactly what is happening here.
I got virtually no feedback, either from the SO community or from Restlets, which actually makes sense given that everything I reported in the question is correct. I decided to attach the Restlet sources to my IntelliJ IDE, and step through the code. I had seen that the Tomcat logs contained a response code of 415, and by inspecting the actual exception inside Restlets, I saw an error stating that the media type I posted was unexpected. Upon seeing this, I immediately knew what I had done wrong, which was:
not sending proper JSON to the login service
not declaring the content type to be JSON in the header of the POSt
and using Restlet services all of which expect JSON
For anyone who faces as similar problem using Restlets with JSON, the following Android code got everything working with no issues:
String endpoint = "http://192.168.0.148:8080/MyApp/service/login";
URL obj = new URL(endpoint);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
JSONObject json = new JSONObject();
json.put("username", username);
json.put("password", password);
// etc.
Recently I started learning android. Now I want know information about web services in android.
which web services are fast in android?
we need to use any libraries for web service fastness?
My main aim is decrease the web service loading time.
Today I observed that web services are taking more time in below API levels and somewhat better in above API levels.
Please any one suggest me how to decrease web service loading.
If you think a library can be used then you may consider using Square Retrofit. With some benchmarks tested, it is quite snappy when considered with async task. Also you can take a look at volley which is also an option in this case but I would recommend Retrofit for its ease of use. you can consider the following article for some metrics.
Android Async HTTP Clients: Volley vs Retrofit.
JSON based web service is lightweight than XML or any other format so even in the low network connectivity you can expect considerable good performance.
Here is a sample code to connect with JSON based web service
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("data", dataValue);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
It's always better to make network calls inside AsyncTask so that you can show progress bar while you are dealing with web service
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.
So basically i need my android app to connect to a web service using a url as such
"http://username:password#0.0.0.0" aka basic authentication.
obviously the username and password are checked by the web app before allowing access and otherwise doesn't allow the request.
my issue is that all the methods i try always say unauthorised (response code 401) regardless of what combination of classes and methods ive used to try and connect to the the url.
The web app in question is designed to return things only is un/pw clears otherwise it returns nothing, the web app and un/pw etc have all be checked and cleared.
so does anyone no the correct way to send a request to a url like that and have it work correctly?
android api8 btw
UPDATE
Turns out my issue is due to the web app using NTLM windows authentication which is not supported directly by androids/apache http library, investigating appropriate workarounds now
Here's some code form a really old project of mine. I used basic auth for some web service, and this worked at the time. I'm not sure if there are updated api's since then (this was Android 1.6), but it should still work.
HttpGet request = new HttpGet();
request.setURI(new URI(url));
UsernamePasswordCredentials credentials =
new UsernamePasswordCredentials(authUser, authPass);
BasicScheme scheme = new BasicScheme();
Header authorizationHeader = scheme.authenticate(credentials, request);
request.addHeader(authorizationHeader);
Basically, Basic HTTP auth is a simple hash of the user and password. The browser allows you to stuff these values in the url, but it actually does the work of adding the basic auth header to your request.
I need to create an Android application, I'm not sure which is a better way of doing this by better I mean should I use the WebView or create an application .
I need to implement the existing application which is a ASP.NET application which mainly consists of a login screen, once the user logs in he will see a list a items in probably a gridview based on the selection from the gridview. He then will be shown more detailed info about the selected item.
The above is a web application I need to implement this as a app on Android phone.
Also there will be a need to use the GPS where based on the GPS values the department will be selected and also use the camera to take a picture and save it on to the server .
A solution which I was thinking of was to expose .NET web services and then access it in the android phone!
But I am very new to Android development and really do not how to go about this. Is there any better solution?
Can anyone help me as to how do I go about this ?
Pros:
Android App may work faster then web applications (but still depends on web page complexity)
By the help of this community and android developer site you can complete your app within a 2-3 weeks.
As you stated picture capture/upload and GPS etc are advantages of the smart phone app.
Cons:
Later, you may need iPhone, Blackberry apps!
Instead of .Net web service which typically returns XML, you can go for HTTP call with JSON response (I've seen it in Asp.net MVC). So that you can easily parse the data on android app.
Added:
HTTP call:
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(getString(R.string.WebServiceURL) + "/cfc/iphonewebservice.cfc?returnformat=json&method=validateUserLogin&username=" + URLEncoder.encode(sUserName) + "&password=" + URLEncoder.encode(sPassword,"UTF-8"));
HttpResponse response = httpClient.execute(httpGet, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
JSONObject JResponse = new JSONObject(sResponse);
String sMessage = JResponse.getString("MESSAGE");
int success = JResponse.getInt("SUCCESS")
There are two approaches available to you:
Build an Android app.
Build a webapp, using W3C geolocation to access GPS coordinates. (see geo-location-javascript)
If you go for option (1), you'll want to expose your .NET service as a simple REST API (using JSON as Vikas suggested to make it just that bit simpler!)
Android already comes with all the components needed to access and parse such a REST API, specifically the Apache HTTP and JSON packages, and can be iterated on rather quickly once you have the basic request/parse framework in place.