2016-07-10 65 views
0

感謝您的時間。我爲學校編寫了一個Android應用程序,並且需要一個用於Moodle登錄的認證表單(服務器以/index.php結尾)。Moodle用外部的Android應用程序(Okhttp)登錄

  1. 我的目標:獲得響應中的「Set-Cookie」標題,其中包含活動的Cookie。如果服務器狀態返回「303(請參閱其他」),則會給出這個結果。
  2. 我的問題:我應該發送到登錄服務器,以獲得狀態「303」(因此也是正確的Cookie)?

我不知道,如果「.add」方法是正確的或錯誤的,或者如果我應該發送更多或更少的服務器。

class MoodleLogin{ 

public static void FirstRequest(String url) throws Exception { 

    final OkHttpClient client = new OkHttpClient(); 

    //FORM BODY 
    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) 
       .build(); 

    // A normal Request 
    Request request = new Request.Builder() 
         .url(url) 
         .post(formBody) 
         .build(); 

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

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

       @Override 
       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()); 

         } 

         response.body().close(); 
        } 
       }); // End of "onResponse" 

} 

代碼的這種和平只返回服務器狀態「200」(什麼是錯在我的情況)。 有誰知道,我必須改變以獲得狀態「303」?我使用hurl.it(HTTP請求的網站)對其進行了測試,並且只有在發佈像普通參數那樣的「用戶名」和「密碼」時纔有效。

我很感激每一個答案和提示!

+0

我的權限:'<使用許可權的android:name = 「android.permission.INTERNET對」/> <使用許可權的android:NAME = 「android.permission.ACCESS_NETWORK_STATE」 />' –

回答

0

我自己回答。因此,這裏是正確的代碼:

      Connection.Response res = Jsoup 
            .connect("your Moodle-Login Page") 
            .data("username", username, "password", password) 
            .method(Connection.Method.POST) 
            .execute(); 

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