java - 如何在改造中获取访问 token

标签 java android get retrofit

我正在创建一个注册应用程序,我已经获得了客户端 ID 和 secret ,现在我必须执行获取请求并获取访问 token 和刷新 token 。我有这个链接https://supptop.mymix.net/api/token?grant_type=password&client_id=yourclientID&client_secret=yourclientSecret&email=email@gmail.com&password=password'

这是界面。

public interface SupportopApi {

@GET("/api/token")
Call<ResponseBody> getToken(@Query("grant_type") String grant_type,
                            @Query("client_id") String client_id,
                            @Query("client_secret") String client_secret,
                            @Query("email") String email,
                            @Query("password") String password);}

好的,现在是下一个类。

public class ApiClient {

private static ApiClient instance;

private SupportopApi supportopApi;

private ApiClient(String endpoint) {

    OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
            .readTimeout(10, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS);

    clientBuilder.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            request = request.newBuilder()
                    .addHeader("Content-Type", "application/json")
                    .build();
            return chain.proceed(request);
        }
    });

    supportopApi = new Retrofit.Builder()
            .baseUrl(endpoint)
            .client(clientBuilder.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(SupportopApi.class);
}

  public Call<ResponseBody> gettoken(String grant_type, String client_id, String client_secret,
                                   String email, String password){

    return supportopApi.getToken(grant_type, client_id, client_secret, email, password);}

好的,这是我打电话的类(class)。

public class FragmentRegistration extends Fragment {
View mainView;

EditText username, email, password, name;
Button button;

ApiClient pentairAPIClient = ApiClient.getInstance();

@Override
public View onCreateView(LayoutInflater inflater,
                         @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    mainView = inflater.inflate
            (R.layout.registration, container, false);

    username = mainView.findViewById(R.id.username);
    email = mainView.findViewById(R.id.email);
    password = mainView.findViewById(R.id.password);
    name = mainView.findViewById(R.id.name);
    button = mainView.findViewById(R.id.register);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String s = name.getText().toString();
            String split[] = s.split(" ");

            updateApp();
        }
    });

    return mainView;
}

public void updateApp() {
    FragmentRegistration context = this;

    Call<ResponseBody> call = pentairAPIClient.registration(supportopObj);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response.isSuccessful()) {
                activationCall();

            } else {
                Toast.makeText(getContext(), "Something went wrong",
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toast.makeText(getContext(), "Error...", Toast.LENGTH_SHORT).show();
        }
    });
}


public void activationCall() {
    Call<ResponseBody> callActive = pentairAPIClient.activation(supportopObjActivate);
    callActive.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {


            if (response.isSuccessful()) {

                try {
                    String data = response.body().string();
                    JSONObject obj = new JSONObject(data);
                    String client_id = obj.getString("client_id");
                    String client_secret = obj.getString("client_secret");


                    Call<ResponseBody> getToken = pentairAPIClient.gettoken("password",client_id, client_secret,
                            email.getText().toString(), password.getText().toString());

                    getToken.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                           if(response.isSuccessful()){
                               Toast.makeText(getContext(), String.valueOf(response.body()), Toast.LENGTH_SHORT).show();
                           }
                           else Toast.makeText(getContext(), "Something wrong", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {
                            Toast.makeText(getContext(), "You're on failure", Toast.LENGTH_SHORT).show();
                        }
                    });


                } catch (JSONException | IOException e) {
                    e.printStackTrace();
                }

            } else
                try {
                    Toast.makeText(getContext(), response.body().string(),
                            Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toast.makeText(getContext(), "Error in activation",
                    Toast.LENGTH_SHORT).show();
        }
    });
}}

我不知道必须将链接粘贴到哪里,我将在哪里包含我的 client_id client_secret、邮件、密码。

最佳答案

尝试使用@Header

https://futurestud.io/tutorials/retrofit-2-manage-request-headers-in-okhttp-interceptor

我认为 client_id 和 client_secret 是 header , grant_type, email , password 是参数。

例如

public class LoginBody {
     private String email;
     private String password;
}

Call<String> call = service.request(AdminTokenUtils.getAuthorizationWeb(),body);

Call<String> request(
            @Header("Authorization") String token,
            @Body LoginBody body
    );

关于java - 如何在改造中获取访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48446618/

相关文章:

android - 使用 phonegap 时未在 android 应用程序中创建 Assets 文件夹

http - URL 查询字符串中的 OR 语句

javascript - 在 GET 中发送 & 号

java 获取字体样式 jtextpane

javascript - 如何从浏览器控制台访问 GWT 的 JsInterop 导出类型?

java - 从调用方法并行执行方法

java - 如何使用 Java 和 JDBC 将文本文件存储在 h2 数据库中?

Android Parse SDK i/o 失败未知格式(魔数(Magic Number) 227b)

带有内部框架的 Java MVC 和复合设计模式

java - 此 NavController 不知道导航 [destination_name]