2

I am building a login application in android in which i am hitting a url(with username and password) upto that part it works fine but after that whenever I am hitting a url(once the user is authenticated) , it return nothing(i.e. a error message like please login first). However it works fine in very similar iphone app and on browser.

I could not understand that what is the actual problem. Is there any problem on server side(i.e. in php coding ) or there is something wrong with android app. We cant actually blame the server side coding because it works fine for same iphone app and on browser.

Any idea or help will be highly appreciated. Thanks.

Dinesh Sharma
  • 11,533
  • 7
  • 42
  • 60

3 Answers3

5

Your Php script uses a session token to identify the visitor when you browse the site via a browser. Ususally its stored in a PHPSESSID variable.

If you want your Android application to stay authenticated on the server side you need to fetch that id after the first connection and then send it in the headers of all your subsequent requests.

**EDIT : ** This is what you want to do : How do I manage cookies with HttpClient in Android and/or Java?

Community
  • 1
  • 1
Yahel
  • 8,522
  • 2
  • 24
  • 32
  • you mean i have to sent that unique id with the url for further request. – Dinesh Sharma May 10 '11 at 09:38
  • Exactly, that way your server will know what session it needs to fetch to see if the user is authenticated. It's really a cookie usually that you need to resend with every request. Take a look here : http://stackoverflow.com/questions/3587254/how-do-i-manage-cookies-with-httpclient-in-android-and-or-java – Yahel May 10 '11 at 09:49
  • But one thing, the same thing is working on the browser and in iphone . So , is this issue only for android and why. Can you give some idea ? – Dinesh Sharma May 10 '11 at 09:51
  • 1
    Because on the browser and probably on your iphone(browser i guess) the browser actually handles the passing of the php session for you via the usage of cookies which it sends automatically to the server in the headers of the requests. – Yahel May 10 '11 at 11:21
  • Thanks , I got your point but can you tell me that how that can be handled in android . – Dinesh Sharma May 10 '11 at 11:23
  • I believe the link that i provided in my question edit should put you on the right track. Basically : Get the session id from the header after your authentification and then send it back with every request as a cookie like the link explains how to. Good luck – Yahel May 10 '11 at 12:04
  • Thanks yahel. I will try this and let you know if the problem continues. Thanks a lot. – Dinesh Sharma May 10 '11 at 12:24
  • @Yahel i have something similar problem can you check it? http://stackoverflow.com/questions/26840060/how-to-pass-id-with-url-while-requesting –  Nov 10 '14 at 09:13
1

You can use an active DefaultHttpClient connection and make validations on each mobile-request, at server side, through $_SESSION. Here is a small sample code (is not for production)

First there is a class:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class NetClient {

    private HttpClient client = null;

    public NetClient() {
        client = new DefaultHttpClient();
    }

    public String request(String url) throws ClientProtocolException, IOException {
        HttpPost post = new HttpPost(url);
        HttpResponse res = client.execute(post);

        BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
        String data = "";
        String line = "";
        while ((line = br.readLine()) != null) {
             data = data + line;
        }
        return data;
    }

    public String login(String url) throws ClientProtocolException, IOException {
        HttpPost post = new HttpPost(url);

        ArrayList pa = new ArrayList();
        pa.add( new BasicNameValuePair( "username", "admin"));
        pa.add( new BasicNameValuePair( "password", "admin"));
        post.setEntity( new UrlEncodedFormEntity(pa, "UTF-8"));

        HttpResponse res = client.execute(post);

        BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
        String data = "";
        String line = "";
        while ((line = br.readLine()) != null) {
             data = data + line;
        }
        return data;
    }
}

Then at mainactivity.java

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

try {
    NetClient n = new NetClient();

    String k = n.login("http://x.com/testAREA/securetrans/login.php");
    Log.w("login result", k);

    String l = n.request("http://x.com/testAREA/securetrans/content.php");
    Log.w("ask if logged in", l);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Where login.php

<?php
session_start();

if(isset($_POST['username']))
{
    $username = $_POST['username'];
    $password = $_POST['password'];

    if($username == 'admin' && $password == 'admin')
    {
        $_SESSION['username'] = $username;

        echo "admin setted";

        exit;
    }
    else
    {
        echo "-1";
    }
}
?>

and content.php as :

<?php
session_start();

if(isset($_SESSION['username']))
{
    echo "login ok";
}
else
{
    echo "not login";
}
?>

When we run this sample code will end with

echo "login ok";

More information at: http://www.pipiscrew.com/2014/11/phpandroid-secure-connection-with-session-variable/

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Zakari
  • 453
  • 4
  • 15
1

I have encountered this very recently, the PHP session was not getting created when we hit the API from Android.

After spending some time, I figured it out.

For creating sessions you need to enable cookies for the API call. you have to set the handler that can accept cookies from incoming HTTP responses and provides cookies to outgoing HTTP requests.

For enabling cookies you have to add cookieJar in your OkHttpClient.

import okhttp3.JavaNetCookieJar
import java.net.CookieManager

    val okHttpClient = OkHttpClient.Builder()
                .cookieJar(JavaNetCookieJar(CookieManager()))
                .build()
Happy Singh
  • 1,334
  • 9
  • 23