2016-03-17 17 views
0

問候我的同胞堆疊開發商,Android的使用消耗2改造與登錄活動的Web API

我有我嘗試使用改造2種請求方式消耗多個ASP.NET端點。我試圖創建一個登錄活動,在輸入和提交憑證後,將POST發送到端點,然後提供令牌信息。需要此身份驗證才能對我試圖在後端訪問的數據使用GET調用。

我目前擁有的登錄活動,以及其餘的適配器和請求方法的接口 - 我失去了我應該如何憑據傳遞給適配器的登錄活動範圍內。

綜上所述,我想輸入的登錄憑據,創建一個POST到端點,並獲得令牌,它帶我到下一個頁面,在這裏我火了實際數據的GET請求。請認識到我是一名.NET開發人員,如果我錯過了難題的大部分內容,請隨時告訴我。任何幫助表示讚賞。

這裏的LoginActivity/MainActivity

import android.app.Activity; 
 
import android.content.Intent; 
 
import android.net.Uri; 
 
import android.os.Bundle; 
 
import android.view.View; 
 
import android.view.View.OnClickListener; 
 
import android.widget.Button; 
 
import android.widget.EditText; 
 
import android.widget.ProgressBar; 
 
import android.widget.TextView; 
 

 
import com.example.smcnary.insightv2.api.ServiceGenerator; 
 

 
public class MainActivity extends Activity { 
 
    //Set Error Status 
 

 
    static boolean errored = false; 
 
    Button b; 
 
    TextView statusTV; 
 
    EditText userNameET , passWordET; 
 
    ProgressBar webservicePG; 
 
    String editTextUsername; 
 
    boolean loginStatus; 
 
    String editTextPassword; 
 
    @Override 
 
    public void onCreate(Bundle savedInstanceState) { 
 
     super.onCreate(savedInstanceState); 
 
     setContentView(R.layout.main); 
 
     //Name Text control 
 
     userNameET = (EditText) findViewById(R.id.editText1); 
 

 
     passWordET = (EditText) findViewById(R.id.editText2); 
 
     //Display Text control 
 
     statusTV = (TextView) findViewById(R.id.tv_result); 
 
     //Button to trigger web service invocation 
 
     b = (Button) findViewById(R.id.button1); 
 
     //Display progress bar until web service invocation completes 
 
     webservicePG = (ProgressBar) findViewById(R.id.progressBar1); 
 
     //Button Click Listener 
 
     b.setOnClickListener(new OnClickListener() { 
 
      public void onClick(View v) { 
 
       //Check if text controls are not empty 
 
       if (userNameET.getText().length() != 0 && userNameET.getText().toString() != "") { 
 
        if(passWordET.getText().length() != 0 && passWordET.getText().toString() != ""){ 
 
         editTextUsername = userNameET.getText().toString(); 
 
         editTextPassword = passWordET.getText().toString(); 
 
         statusTV.setText(""); 
 
         Intent intent = new Intent(
 
           Intent.ACTION_VIEW, 
 
           Uri.parse(ServiceGenerator.API_BASE_URL + "/token" + "?client_id=" + userNameET)); 
 
          startActivity(intent); 
 

 
        } 
 
        //If Password text control is empty 
 
        else{ 
 
         statusTV.setText("Please enter Password"); 
 
        } 
 
        //If Username text control is empty 
 
       } else { 
 
        statusTV.setText("Please enter Username"); 
 
       } 
 
      } 
 
     }); 
 
    } 
 

 

 
}

適配器/ ServiceGenerator:

import android.util.Base64; 
 
import com.example.smcnary.insightv2.model.User; 
 
import java.io.IOException; 
 
import okhttp3.Interceptor; 
 
import okhttp3.OkHttpClient; 
 
import okhttp3.Request; 
 
import okhttp3.Response; 
 
import retrofit.Callback; 
 
import retrofit2.Call; 
 
import retrofit2.Retrofit; 
 
import retrofit2.converter.gson.GsonConverterFactory; 
 
import retrofit2.http.Field; 
 
import retrofit2.http.FormUrlEncoded; 
 
import retrofit2.http.POST; 
 

 
public class ServiceGenerator { 
 

 
    public static final String API_BASE_URL = "http://figgg-identity.azurewebsites.net/token"; 
 

 
    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); 
 

 
    private static Retrofit.Builder builder = 
 
      new Retrofit.Builder() 
 
        .baseUrl(API_BASE_URL) 
 
        .addConverterFactory(GsonConverterFactory.create()); 
 

 
    public static <S> S createService(Class<S> serviceClass) { 
 
     return createService(serviceClass, null, null); 
 
    } 
 

 
    public static <S> S createService(Class<S> serviceClass, String username, String password) { 
 
     if (username != null && password != null) { 
 
      String credentials = username + ":" + password; 
 
      final String basic = 
 
        "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); 
 

 
      httpClient.addInterceptor(new Interceptor() { 
 
       @Override 
 
       public Response intercept(Interceptor.Chain chain) throws IOException { 
 
        Request original = chain.request(); 
 

 
        Request.Builder requestBuilder = original.newBuilder() 
 
          .header("Authorization", basic); 
 
        requestBuilder.header("Accept", "application/json"); 
 
        requestBuilder.method(original.method(), original.body()); 
 

 
        Request request = requestBuilder.build(); 
 
        return chain.proceed(request); 
 
       } 
 
      }); 
 
     } 
 

 
     OkHttpClient client = httpClient.build(); 
 
     Retrofit retrofit = builder.client(client).build(); 
 
     return retrofit.create(serviceClass); 
 
    } 
 

 
    public interface LoginService { 
 
     @FormUrlEncoded 
 
     @POST("/token") 
 
     User Basiclogin(@Field("email") String email, @Field("password") String password, Callback<User> callback); 
 

 

 
    } 
 

 

 
}

編輯:這是我的JSON對象:

的authToken:

package com.example.smcnary.insightv2.model; 
 

 
import java.util.HashMap; 
 
import java.util.Map; 
 

 

 

 
public class AuthToken { 
 

 
    private String accessToken; 
 
    private String tokenType; 
 
    private Integer expiresIn; 
 
    private String name; 
 
    private String title; 
 
    private String picImageBase64String; 
 
    private String Issued; 
 
    private String Expires; 
 
    private Map<String, Object> additionalProperties = new HashMap<String, Object>(); 
 

 
    /** 
 
    * 
 
    * @return 
 
    * The accessToken 
 
    */ 
 
    public String getAccessToken() { 
 
     return accessToken; 
 
    } 
 

 
    /** 
 
    * 
 
    * @param accessToken 
 
    * The access_token 
 
    */ 
 
    public void setAccessToken(String accessToken) { 
 
     this.accessToken = accessToken; 
 
    } 
 

 
    /** 
 
    * 
 
    * @return 
 
    * The tokenType 
 
    */ 
 
    public String getTokenType() { 
 
     return tokenType; 
 
    } 
 

 
    /** 
 
    * 
 
    * @param tokenType 
 
    * The token_type 
 
    */ 
 
    public void setTokenType(String tokenType) { 
 
     this.tokenType = tokenType; 
 
    } 
 

 
    /** 
 
    * 
 
    * @return 
 
    * The expiresIn 
 
    */ 
 
    public Integer getExpiresIn() { 
 
     return expiresIn; 
 
    } 
 

 
    /** 
 
    * 
 
    * @param expiresIn 
 
    * The expires_in 
 
    */ 
 
    public void setExpiresIn(Integer expiresIn) { 
 
     this.expiresIn = expiresIn; 
 
    } 
 

 
    /** 
 
    * 
 
    * @return 
 
    * The name 
 
    */ 
 
    public String getName() { 
 
     return name; 
 
    } 
 

 
    /** 
 
    * 
 
    * @param name 
 
    * The name 
 
    */ 
 
    public void setName(String name) { 
 
     this.name = name; 
 
    } 
 

 
    /** 
 
    * 
 
    * @return 
 
    * The title 
 
    */ 
 
    public String getTitle() { 
 
     return title; 
 
    } 
 

 
    /** 
 
    * 
 
    * @param title 
 
    * The title 
 
    */ 
 
    public void setTitle(String title) { 
 
     this.title = title; 
 
    } 
 

 
    /** 
 
    * 
 
    * @return 
 
    * The picImageBase64String 
 
    */ 
 
    public String getPicImageBase64String() { 
 
     return picImageBase64String; 
 
    } 
 

 
    /** 
 
    * 
 
    * @param picImageBase64String 
 
    * The picImageBase64String 
 
    */ 
 
    public void setPicImageBase64String(String picImageBase64String) { 
 
     this.picImageBase64String = picImageBase64String; 
 
    } 
 

 
    /** 
 
    * 
 
    * @return 
 
    * The Issued 
 
    */ 
 
    public String getIssued() { 
 
     return Issued; 
 
    } 
 

 
    /** 
 
    * 
 
    * @param Issued 
 
    * The .issued 
 
    */ 
 
    public void setIssued(String Issued) { 
 
     this.Issued = Issued; 
 
    } 
 

 
    /** 
 
    * 
 
    * @return 
 
    * The Expires 
 
    */ 
 
    public String getExpires() { 
 
     return Expires; 
 
    } 
 

 
    /** 
 
    * 
 
    * @param Expires 
 
    * The .expires 
 
    */ 
 
    public void setExpires(String Expires) { 
 
     this.Expires = Expires; 
 
    } 
 

 
    public Map<String, Object> getAdditionalProperties() { 
 
     return this.additionalProperties; 
 
    } 
 

 
    public void setAdditionalProperty(String name, Object value) { 
 
     this.additionalProperties.put(name, value); 
 
    } 
 

 
}

用戶對象:

public class User { 
 
    @SerializedName("name") 
 
    String name; 
 
    @SerializedName("email") 
 
    String email; 
 
}

回答

0

我不知道這是否是一個很好的做法,但我保存用戶憑據在SharedPreferences並將其保存在您的應用程序(在你的應用類中創建一個單身或使用匕首來構建它),直到signout行動發生在。我使用Authenticatorhttps://square.github.io/okhttp/3.x/okhttp/okhttp3/Authenticator.html。例如,我們可以選擇使用UserCredentials類那些憑證存儲,那麼當OkHttp客戶構建體,我們可以通過參數傳遞給它。

OkHttpClient provideOkHttpClient(UserCredentials userCredentials) { 

     return new OkHttpClient.Builder() 
       .authenticator(new CustomAuthenticator(userCredentials)) 
       .build(); 
    } 

隨着CustomAuthenticator是這個樣子:

public class CustomAuthenticator implements Authenticator { 

    @NonNull 
    private final UserCredentials credentials; 

    public CustomAuthenticator(@NonNull UserCredentials credentials) { 
     this.credentials = credentials; 
    } 

    @Override 
    public Request authenticate(Route route, Response response) throws IOException { 
     String userToken = credentials.getToken(); 
     return response.request().newBuilder() 
       .header("Authorization", "Token " + userToken) 
       .build(); 
    } 
} 

有基本的登錄方法爲好。您可以從鏈接中閱讀並嘗試。