Android connection with ASP.NET MVC4 - android

I just created an MVC4 WebApplication. This application is using a database (created by CodeFirst) which contains the user info (aspnet Membership) and all the other info.
I'm now trying to make an Android app which uses the same database as the MVC4 Webapplication. But I have no clue how I can implement the login system.
I was thinking about sending a post request to the server (local for the moment) with the username and password. (will be encrypted later). But I have no clue how I can do this.
Can anyone help me out with the login system?
Should I make some changes to my Webapplication to achieve my goal?
Thanks in advance !
UPDATE
I now tried the following:
I just wrote the following function which I run when I press my button
android:onClick="login"
My java function:
public void login(){
String userName = "Isf";
String password = "admin123!";
HttpClient httpClient = new DefaultHttpClient();
//I run my MVC Application local
//Logon page: http://localhost:2657/Account/LogOn
HttpPost httpPost = new HttpPost("http://10.0.2.2/Account/LogOn");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", userName));
nameValuePairs.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Response from the Http Request
HttpResponse response = httpClient.execute(httpPost);
} catch (IOException e) {
Log.e("Exception", "IOException", e);
} catch (Exception e) {
Log.e("Exception", "General Exception", e);
}
}
But when I run my MVC project and I press my login button on Android, I get the following message:
"The application login (proces com.example.login) has stopped unexpectedly. Please try again."
(I tried it with my phone, and with the emulator)
Does anyone know what I'm doing wrong?

Are you using asyncTasks? Requests cant be send in the main thread, asynctask is going to create a new thread. There is some good documentation on developer site from android: asynctask

You can use HTTP to send and receive data
http://www.jiahaoliuliu.com/2012/04/android-http-client-login.html
Make an HTTP request with android
http://developer.android.com/reference/org/apache/http/client/HttpClient.html

Related

Http get pass parameters

Im new to Android development but Im trying to do an application for Opencart to allow users to enter in their own store to administrate it.
Lets go to the point. In order to get the information from the store i created a page where all the information is presented in XML, so the idea is that the user login, and then redirects to this page and with the http response, parse the xml and voilá!.
I have already the xml parser, but Im having some difficulties with the http connection. Let me explain a little bit more:
Basically, to log into any store, you need to go to www.example.com/admin (I will be using my testing online address to see if someone is able to help me), in this case http://www.onlineshop.davisanchezplaza.com/admin . Once we arrive to the page we arrive to the login system. The login system uses post to send the username: admin and password:admin and redirects to http://onlineshop.davidsanchezplaza.com/admin/index.php?route=common/login and once it verify your identity, it gives you a Token (here I start having some problems). http://onlineshop.davidsanchezplaza.com/admin/index.php?route=common/home&token=8e64583e003a4eedf54aa07cb3e48150 . Well, till here, im very okay, and actually developed an app that can do till here, actually i can "hardcode" read the token from the http response it sends me (what is actually not very good).
Here comes my first question: HOW TO GET FROM THE HTTPresponse the token value? (by now, as I said, I can only get the token by reading all the response, and if we find the string token=, take what comes next ... not good).
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), TIMEOUT_MS);
HttpConnectionParams.setSoTimeout(httpClient.getParams(), TIMEOUT_MS);
HttpPost httpPost = new HttpPost("http://onlineshop.davidsanchezplaza.com/admin/index.php?route=common/login");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", "admin"));
nameValuePairs.add(new BasicNameValuePair("password", "admin"));
try{
Log.d(DEBUG_TAG, "Try ");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 8096);
Log.d(DEBUG_TAG, "br :" + br);
String line;
while ((line = br.readLine()) != null) {
Log.d(DEBUG_TAG, "br :" + line);
if(line.contains("token=")){
int index = line.indexOf("token=");
String aux = line.substring(index + "token=".length(), index + 32 + "token=".length());
token = aux; //Yes, I know, its not the best way.
break;
}
}
} catch (IOException e) {
Log.d(DEBUG_TAG, "Finally");
}
Second question, (and more important), now having the token (in the example 8e64583e003a4eedf54aa07cb3e48150), I need to go to the route android/home where is the xml information generated. (http://onlineshop.davidsanchezplaza.com/admin/index.php?route=android/home2&token=8e64583e003a4eedf54aa07cb3e48150). As I was reading, in httpget, we can either set the parameters, or directly send the url with the parameters already inside the url. Is in this step where it stops. Maybe is the internet connexion in China, maybe (most sure) im doing something wrong. Sometimes it just come the timeout connexion, others it just send me back to the login page.
Here is the code how i do (edit: I was a noob, and didnt create the httpclient to receive the answer, sorry!):
String s = "http://onlineshop.davidsanchezplaza.com/admin/index.php?route=common/home&token=";
String tot = s.concat(token);
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), TIMEOUT_MS);
HttpConnectionParams.setSoTimeout(httpClient.getParams(), TIMEOUT_MS);
HttpGet httpget = new HttpGet(tot);
try{
Log.d(DEBUG_TAG, "Try ");
HttpResponse response = httpClient.execute(httpget);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 8096);
Log.d(DEBUG_TAG, "br :" + br);
} catch (IOException e) {
Log.d(DEBUG_TAG, "Finally");
}
I dont need someone to tell me how to do it, just need a little guidance to solve the issue, I really appreciate any comment or help you can offer, or extra documentation :).
As a bonus, if someone can give me further details about how can I test the http get, I will appreciate, I only know how to write it in the web browser, and works fine.
It's a while since I last did something for Android, but here is my advice:
for the login purpose from Android application into the OpenCart administration I recommend creating a new mobile login page, e.g. instead of accessing http://yourstore.com/admin/ which redirects You to http://.../admin/index.php?route=common/login create Your own action e.g. androidLogin() within this controller (admin/controller/common/login.php and You will access it directly via http://yourstore.com/admin/index.php?route=common/login/androidLogin. Why special action? Because the default login action redirects the user (using normal browser) to the home while setting the security token into the URL within the query string part. In Your own action You won't redirect but respond with XML containing this security token so that You can easily extract that token using Your XML parser.
I cannot address second problem exactly but from what I remember I was passing a query string in different way (now I cannot find any similar solution on the internet).
Here is my 5 cents for the second question :
After playing a bit with the browser I realized :
Set Cookies
Your request to ...?route=android/home2&token= seems to be rejected if you are missing cookies. That is, you probably need to extract cookies from first server response and set them for further requests either manually (via conn.setRequestProperty("Cookie", cookie); or using Android CookieManager
User agent
Some server may reject your request just because you are missing "User-Agent" property in request header. To be safe, you could set it to something like conn.setRequestProperty("User-Agent", "Mozilla/5.0");
Extra note - I suggest that you also handle redirects correctly, as for example when you POST your admin/admin credentials you get 302 response and redirected to ...?route=common/home page
Also, you don't need to set conn.setDoInput(true) for UrlConnection while doing GET request.
Hope that helps.
I don't see any catch statement for the try in the second question, this catch may have the info you need to know what's going on.
For the first question try to convert InputStreamReader to a String, and use the String for a
url constructor, with the url (or uri i'm not sure right now, and can't test it) object try .getQueryParameter("parameter").
For your second question when i tried to login using the token that you have provided, the web page replied with invalid token. Can you login with the token that you have provided? If not, try to get a new token. Maybe the token have expired.

How to execute RESTful POST requests from Android

I'm trying to execute a REST Post for the first time and I don't quite know where to begin.
I'm interacting with the WordPress REST API, and am trying to utilize this endpoint: /sites/$site/posts/$post_ID/replies/new, which is used to submit a new comment to a certain post.
I think I have a good grasp on working with GET requests, as I've successfully handled several of them. With those, I could say everything I needed to say to the server vis a vis the URL, but it seems there must be another step with POST requests. And my question is: What is that step(s)?
Do I wrap the content I want to submit into a JSONObject and post that? If so, how do I post it? Do I need to construct a statement somehow, similar to how I would construct a statement to execute on a database? Or is it indeed possible to pass my content along via the URL, as request parameters?
I'm aware that this question is a little on the open-ended side for SO, but I've been unable to find a good tutorial that answers these questions. If you know of one, please suggest it.
(I'm doing this all in an Android app)
My answer is taken straight from another answer on SO seen here Sending POST data in Android but ive cut and past the answer here for conveneience, Hope this helps
Http Client from Apache Commons is the way to go. It is already included in android. Here's a simple example of how to do HTTP Post using it.
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
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);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
You need to implement a script on your server, your POST interacts with that script and inturn that script works with your database.
A typical scenario will be:
Java HTTP POST ~~~> PHP ~~~~> MySql.
A good starting point to learn PHP will be to checkout PHPAcademy tutorials on youtube.
http://www.youtube.com/course?list=EC442FA2C127377F07
PHP will as well help you encode the result in JSON and post it back to your client.

Android Login to Website - POST Request Crashing App

I have a site that I would like to log into. Once there, I would parse the code to display member data (like any other login app). I have sort of pulled this code from somewhere and I'd like to know why it's crashing. Basically, I have two login inputs, username and password. I'll take them from the user but as of now I'm just inputting random credentials for testing. At the end, I want to get it to the login page (same url once logged in) and display the HTML, for now.
Here's my code so far:
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), TIMEOUT_MS);
HttpConnectionParams.setSoTimeout(httpClient.getParams(), TIMEOUT_MS);
HttpPost httpPost = new HttpPost("login url"); // Removed for StackOverflow question
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("sid", "name"));
nameValuePairs.add(new BasicNameValuePair("pin", "pass"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 8096);
tvStatus.setText((CharSequence) br);
Are you running the POST request on the UI thread? This causes the UI to freeze and after a certain time period, the OS considers the app to be non-responsive and force closes it. Web Requests should always be an Async task
I guess this post on my blog will help you to understand, how to use AsyncTask, for downloading stuff.
Though if you tell us what is the Exception which is getting thrown up, I could've helped you more on this. To see the Exception, open the LogCat,identify the error text which will be in red, copy the whole red text and paste it into your question.

Download Data from Server in android 2.1

I want to download some contacts saved on my online server and then display them in my activity. I have written a service and I am giving the code snippet from onStartCommand function, where this downloading is being done.
public int onStartCommand(Intent intent, int flags, int startId)
{
String responseStr = "";
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "get_contact"));
nameValuePairs.add(new BasicNameValuePair("uId", uId + ""));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
BufferedReader in = new BufferedReader (new InputStreamReader(httpResponse.getEntity().getContent()));
responseStr = in.readLine();
in.close();
}
catch (ClientProtocolException e)
{
Log.e("EXCEPTION", "ClientProtocolException");
}
catch (IOException e)
{
Log.e("EXCEPTION", "IOException");
}
this.stopSelf();
return Service.START_STICKY;
}
But the problem with this code is that it takes too much time to download the data. Kindly suggest me any way to download and display this data in my activity quickly.
Thanks in advance for your help.
Well, if your server or connection is slow, there is not much you can do with your client code.
But, you should definitely consider compressing the responses from your web server and on the client code, add the header:
Accept-Encoding: gzip
There is no guarantee that you will not experience slow download or timeouts even after you enable compression at the HTTP level. At the end of the day you are dealing with unbounded data set and what works in your development environment may not work in the field with a very slow connection where a user may have 25000 contacts all with very long name.
It might be worth looking at the problem in general, considering whether you really need to load all the data right away. You may want to use some sort of pagination (see this question for example and/or use EndlessAdapter).
Try using a socket connection instead.
The thing I notice is you are not doing the download as a background task. Unless your service is running as a separate process from your main activity then this code will execute in the main application (UI) thread of the application and will negatively affect your users. I would recommend you move the code to a AsyncTask or thread launched from onStartCommand. I would then utilize a callback from the service to notify the activity that data is available to display. Also as Dmitry recommends, pagination could help you out as well for the actual download duration.

Trying to send a string from an Android emulator to a webservice

I'm trying to write a java code on an Android emulator that will send a string to a web service writen in c#.
Android code:
HttpPost httppost = new HttpPost("http://192.168.2.1:53811/WinnerSite/WebService.asm/MyMethod
try {
// Add your data
List nameValuePairs = new ArrayList(2);
nameValuePairs.add(new BasicNameValuePair("json", name));
// nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
Also tried:
HttpPost httppost = new HttpPost("http://192.168.2.1:53811/WinnerSite/WebService.asm/MyMethod
The web-service is on the same machine as the emulator. MyMethod is accessable through:
http://localhost:53811/WinnerSite/WebService.asmx/MyMethod
Does someine ahs an idea?
The code exits on the "httpclient.execute(httppost);" line
The eclipse shows:
"ActivityThread.prefo
Source not found."
I have already solve a persmission problem (adding a note to the emolator's xml)
Thanks,
When you want to use the network, you should add network access permission in your AndroidManifest.xml.
Your problem seems to be complex. Check your client app and web service separately to assure they are both correct.
Your codes posted seems to be correct. But your error message "ActivityThread.prefo Source not found." is too weak... Please provide more info.

Categories

Resources