Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

It's a while since I last did something for Android, but here is my advice:

  1. 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.

  2. 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).

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top