2016-07-10 61 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);