Reddit oAuth 2 for Android"无用户"应用程序,带有Retrofit

Vik*_*ool 5 android oauth reddit oauth-2.0 retrofit

我正在尝试在基于Android的"无用户"应用程序中实现Reddit oAuth2(每个使用Reddit内容的应用程序都必须实现此功能)并且我遵循指南.

  1. 注册了一个应用程序并获得相应的client_id.
  2. 我正在关注此指南以获取API指南,并将其用于Retrofit,以便正确编写Android代码.

因此,我已经编写了两种方法来解决这个问题,似乎两种方法都不起作用.适当的片段中的调用对于这两个选项是相同的,它如下所示:

    public void oAuth(){

    String bodyString = "grant_type=" + "https://oauth.reddit.com/grants/installed_client"
                       + "&device_id=" + UUID.randomUUID().toString();

    TypedInput requestBody = new TypedByteArray("application/x-www-form-urlencoded", bodyString.getBytes(Charset.forName("UTF-8")));

    RedditAPI.sRedditAuth().redditAuth(requestBody, new Callback<TokenResponse>() {
        @Override
        public void success(TokenResponse tokenResponse, Response response) {
            Log.d("OATH_TAG", "oAuth() | YAY! :)");
        }

        @Override
        public void failure(RetrofitError error) {
            Log.d("OATH_TAG", "oAuth() | NOOOOOoooooo.... :(");
        }
      });
    }
Run Code Online (Sandbox Code Playgroud)

选项1:

  • 改造界面:

      public interface RedditAuthInterface {
      @POST(Urlz.REDDIT_OATH2_PATH)
      void redditAuth(@Body TypedInput body, Callback<TokenResponse> result);
    
     }
    
       //the adapter
       public static RedditAuthInterface sRedditAuth() {
       if (sRedditAuthInterface == null) {
       RestAdapter restAdapter = new RestAdapter
                                      .Builder()
                                      .setClient(getAuthClient())
                                      .setEndpoint(Urlz.BASE_REDDIT_URL)
                                      .build();
        sRedditAuthInterface = restAdapter.create(RedditAuthInterface.class);
      }
    
      return sRedditAuthInterface;
     }
    
    
    /* support methods */
    private static OkClient getAuthClient() {
    
    final OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setReadTimeout(Static.READ_TIMEOUT, TimeUnit.SECONDS);
    okHttpClient.setConnectTimeout(Static.CONNECT_TIMEOUT, TimeUnit.SECONDS);
    /*okHttpClient.setAuthenticator(new Authenticator() {
        @Override
        public Request authenticate(Proxy proxy, Response response) throws IOException {
            String credential = Credentials.basic(BldCnfg.REDDIT_CLIENT_ID, BldCnfg.REDDIT_PASS);
            return response.request().newBuilder().header("Authorization", credential).build();
        }
    
        @Override
        public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
            return null;
        }
     });*/
    
     okHttpClient.networkInterceptors().add(OAUTH_INTERCEPTOR);
    
      return new OkClient(okHttpClient);
    }
    
    private static final Interceptor OAUTH_INTERCEPTOR = new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        String credentials = BldCnfg.REDDIT_CLIENT_ID + ":" + BldCnfg.REDDIT_PASS; // REDDIT_PASS = "" as by API guides
        String string = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
    
        originalResponse.header("Authorization", string);
        originalResponse.header("Accept", "application/json");
        return originalResponse;
         }
     };
    
    Run Code Online (Sandbox Code Playgroud)
  • 结果:

RetrofitError:401未经授权

方案2:

  • 改造界面:

       public interface RedditAuthInterface {
      @POST(Urlz.REDDIT_OATH2_PATH)
      void redditAuth(@Body TypedInput body, Callback<TokenResponse> result);
    
       }
    
    
         //the adapter
          public static RedditAuthInterface sRedditAuth() {
          if (sRedditAuthInterface == null) {
        RestAdapter restAdapter = new RestAdapter
                                      .Builder()
                                      .setClient(getConfuguredClient())
                                        .setRequestInterceptor(getRequestInerceptorPass())
                                      .setEndpoint(Urlz.BASE_REDDIT_URL)
                                      .build();
        sRedditAuthInterface = restAdapter.create(RedditAuthInterface.class);
    }
    
    return sRedditAuthInterface;
    }
    
    
    /* support methods */
    
    public static RequestInterceptor getRequestInerceptorPass() {
    RequestInterceptor rqInter = new RequestInterceptor() {
        @Override
        public void intercept(RequestFacade request) {
    
            String credentials = BldCnfg.REDDIT_CLIENT_ID + ":" + BldCnfg.REDDIT_PASS; // REDDIT_PASS = "" as by API guides
            String string = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
            request.addHeader("Authorization", string);
            request.addHeader("Accept", "application/json");
          }
        };
    
    return rqInter;
    }
    
    
    private static OkClient getConfuguredClient() {
    
    final OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setReadTimeout(Static.READ_TIMEOUT, TimeUnit.SECONDS);
    okHttpClient.setConnectTimeout(Static.CONNECT_TIMEOUT, TimeUnit.SECONDS);
    return new OkClient(okHttpClient);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 结果:

似乎我得到空响应(我只获得范围的"*").成功的响应如下:

在此输入图像描述

和标头像这样:

在此输入图像描述

你有什么想法我做错了吗?有人这样做过吗?

官方的Reddit github wiki缺少Android示例(几乎所有其他语言都有).

小智 0

我之前也遇到过同样的问题,并让这个在 Android 中处理 OAuth2。该库是 Retrofit 的扩展,可简化 OAuth 2 提供商的身份验证过程。