P.Lenert P.Lenert - 2 months ago 19x
Android Question

Moodle Login with an external Android App (Okhttp)

Thanks for your time. Im programming an Android App for School and need a Authentification Form for the Moodle Login (Server ends with /index.php).

  1. My Goal: Get the "Set-Cookie" Header in the Response with the active Cookie in it. This is given, if the Server Status returnes "303(See Other)".

  2. My Question: What should I post to the Login Server, to get the Status "303" (and therefore also the right Cookie) ?

I dont know, if the ".add" Method is the right or wrong or if I should send more or less to the Server.

class MoodleLogin{

public static void FirstRequest(String url) throws Exception {

final OkHttpClient client = new OkHttpClient();

RequestBody formBody = new FormBody.Builder()
.add("username", USERNAME) // Username
.addEncoded("password", PASSWORT) //Passwort
.add("token", "6f65e84f626ec97d9eeee7ec45c88303") //Security Key for Moodle mobile web service (I dont know if I need that)

// A normal Request
Request request = new Request.Builder()

// Asynchronous Call via Callback with onFailure and onResponse
client.newCall(request).enqueue(new okhttp3.Callback() {

public void onFailure(Call call, IOException e) {
Log.i("Internet", "request failed: " + e.toString());

public void onResponse(Call call, Response response) throws IOException {

if (!response.isSuccessful()) { // Server Status is not 200 - THAT IS WHAT I WANT

Log.d("Server Status", response.message().toString());

throw new IOException("Unexpected code ");

} else { // Server Status is 200(OK)

Log.d("Server Status", response.message().toString());


}); // End of "onResponse"


This peace of Code only returns the Server Status "200" (what is wrong in my case).
Do anyone know, what I must change to get the Status "303" ? I tested it with hurl.it (A Website for HTTP Requests) and it works only if I post the "username" and "password" like normal Parameters.

Im grateful for every answer and tip !


I answered it myself. So here is the right code:

                            Connection.Response res = Jsoup
                                    .connect("your Moodle-Login Page")
                                    .data("username", username, "password", password)

                            String Login_cookies = res.cookies().toString();
                            String cookie = Login_cookies.substring(1, 50);
                            System.out.println("COOKIES: "+cookie);