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.
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
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.
Im coding a RESTful API & Android client at the same time as I go and im currently working on pulling the users profile from the server. I feel like this should definitely be a get request being that im only pulling existing data and im not adding/editing anything to my database, but I do need a user_id param to be able to query for the appropriate profile. Can I send just one tiny little variable along with my HttpGet some how or am i supposed to use a HttpPost in this situation regardless?
Android uses Apache's HTTPClient. So, copying their tutorial code:
public void sendStringTo(String remoteUrl, String myString) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(remoteUrl+"?string1="+myString);
HttpResponse response1 = httpclient.execute(httpGet);
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST either fully consume the response content or abort request
// execution by calling HttpGet#releaseConnection().
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity1);
} finally {
httpGet.releaseConnection();
}
return;
}
GET can support adding variables/parameters. For example you could make a Url that looks like this:
http://yourwebsite.com/script.php?user_id=19898424
I'm working on an android app that has to send and receive information from a 3rd party server. I'm not experienced at this at all, so bear with me if I give too much/too little/not the right kind of information at first.
The API that was provided to send information has the format
https://methodurl.com/username=user&password=pass&key=key&info=infotosend
When I put this URL into my desktops browser, it returns a string, which I'm also trying to get. At least, I'm assuming all it returns is a string, since if I look at the page source, there is just a string, such as "200 OK" or "401 Unauthorized".
The code I'm using is what I can glean from the web what I'm supposed to use. Unfortunately, for all I know, I'm writing code to do something very different than what I want. I've never written code to interact with a server before, so this is all new to me.
Here's my code:
TextView urlView = (TextView)findViewById(R.id.url_view);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(siteToSubmit);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
String serverResponse = client.execute(request, responseHandler);
urlView.setText(serverResponse);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Logcat in eclipse (when app is running on the emulator) is
java.net.UnknownHostException
The way I understand the code to be working is I'm creating a client that will execute on a url (like would happen when I hit enter in the URL bar on a browser), a request for that client to execute on, and a handler to receive the response from the server, which is set to be recieved as a string. I am then trying to set that string as the text in a TextView to verify that I am getting the proper response. Right now, I just get the log error, and urlView does not change. Any ideas why? Am I understanding the process correctly?
Thanks!
Add the uses-permission android.permission.INTERNET to the manifest file.