如何在改造后的请求中设置标题?

时间:2017-07-15 10:23:40

标签: android

我正在尝试实现MSG91的sendOTP。我必须使用API​​,一个用于生成otp,另一个用于验证otp.But在post reuest中我必须设置标头,所以如何在改造中设置标头。我附上了一张关于该做什么的图片。请帮助我。enter image description here

发布请求: -

public class GenerateOTPRequest {
    String countryCode;
    String mobileNumber;

    public GenerateOTPRequest(String countryCode, String mobileNumber) {
        this.countryCode = countryCode;
        this.mobileNumber = mobileNumber;
    }

    public String getCountryCode() {
        return countryCode;
    }

    public void setCountryCode(String countryCode) {
        this.countryCode = countryCode;
    }

    public String getMobileNumber() {
        return mobileNumber;
    }

    public void setMobileNumber(String mobileNumber) {
        this.mobileNumber = mobileNumber;
    }
}

响应: -

public class GenerateOTPResponse {

    @SerializedName("status")
    @Expose
    String status;

    @SerializedName("response")
    @Expose
    String response;

    public GenerateOTPResponse(String status, String response) {
        this.status = status;
        this.response = response;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getResponse() {
        return response;
    }

    public void setResponse(String response) {
        this.response = response;
    }
}

我的主要活动: -

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_verify_otp);

    CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
            .setDefaultFontPath("fonts/opensanslight.ttf")
            .setFontAttrId(R.attr.fontPath)
            .build()
    );


    getSupportActionBar().setTitle("Verify Your OTP");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);



    enterOTP = (EditText) findViewById(R.id.enter_otp);
    verifyOTP = (Button) findViewById(R.id.verify_otp);
    didntReceiveOTP = (TextView) findViewById(R.id.verify_otp_didnt_receive_otp);

    sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
    phone = sharedpreferences.getString(Phone, "notPresent");
    Log.d("jkhdds:  ", "" + phone);


   GenerateOTPRequest generateOTPRequest = new GenerateOTPRequest("","");
    generateOTPRequest.setCountryCode("91");
    generateOTPRequest.setMobileNumber(phone);


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

                                      Request request = original.newBuilder()
                                              .header("application-key", "oEBg-3z4hgcv5X8sk_AYdVDiqpGCN02G3cFRjCK0er6MWhuSHAQDRT3TuJKxzOI__2H3D_gZZWeMJsns92zEm4LlksdilXYePbiFZRc1OLZxZd1DmSQOlmM-MIhDrXOqefgIVJX_deqP0QfRoBZ-PtlqpCtZFRqem1kl_J2Vra8=")
                                              .method(original.method(), original.body())
                                              .build();

                                      return chain.proceed(request);
                                  }
                              });


    OkHttpClient client = httpClient.build();
    Retrofit retrofit1 = new Retrofit.Builder()
            .baseUrl("https://sendotp.msg91.com/api/")
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();


    final API service1 = retrofit1.create(API.class);


    Call<GenerateOTPResponse> call = service1.generateOTP(generateOTPRequest);
    call.enqueue(new Callback<GenerateOTPResponse>() {
        @Override
        public void onResponse(Call<GenerateOTPResponse> call, retrofit2.Response<GenerateOTPResponse> response) {
            //GenerateOTPResponse generateOTPResponse = response.body();
            //String status = otpResponse.getStatus();

            Log.d("otp response " , response.body().getResponse());


        }

        @Override
        public void onFailure(Call<GenerateOTPResponse> call, Throwable t) {

        }
    });

    Log.d("Tag", String.valueOf(enterOTP.getText()));





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

            Request request = original.newBuilder()
                    .header("application-key", "oEBg-3z4hgcv5X8sk_AYdVDiqpGCN02G3cFRjCK0er6MWhuSHAQDRT3TuJKxzOI__2H3D_gZZWeMJsns92zEm4LlksdilXYePbiFZRc1OLZxZd1DmSQOlmM-MIhDrXOqefgIVJX_deqP0QfRoBZ-PtlqpCtZFRqem1kl_J2Vra8=")
                    .method(original.method(), original.body())
                    .build();

            return chain.proceed(request);
        }
    });


    OkHttpClient client1 = httpClient1.build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://sendotp.msg91.com/api/")
            .addConverterFactory(GsonConverterFactory.create())
            .client(client1)
            .build();

    final API service = retrofit.create(API.class);

    Log.d("Tag",enterOTP.getText().toString());

    Log.d("Tag","fuck u");


    verifyOTP.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final VerifyOTPRequest verifyOTPRequest = new VerifyOTPRequest("","","");
            verifyOTPRequest.setCountryCode("91");
            verifyOTPRequest.setMobileNumber(phone);
            verifyOTPRequest.setOneTimePassword(enterOTP.getText().toString());
            Log.d("Tag",enterOTP.getText().toString());

            Call<VerifyOTPResponse> call = service.verifyOTP(verifyOTPRequest);
            call.enqueue(new Callback<VerifyOTPResponse>() {
                @Override
                public void onResponse(Call<VerifyOTPResponse> call, retrofit2.Response<VerifyOTPResponse> response) {
                    Log.d("Tag", String.valueOf(response.body()));
                    String message = response.body().getStatus();
                    Log.d("Tag",message);
                    if (message.equals("success")) {
                        Toast.makeText(getApplicationContext(), "Successfully Verified", Toast.LENGTH_LONG).show();
                        Intent intent1 = getIntent();
                        String parentActivityName = intent1.getStringExtra("activity");
                        if (parentActivityName.equals("signup")) {
                            Intent selectSubject = new Intent(VerifyOTPActivity.this, SelectSubjectActivity.class);
                            progressDialog.dismiss();
                            startActivity(selectSubject);
                        } else {
                            Intent changepassword = new Intent(VerifyOTPActivity.this, ChangePasswordActivity.class);
                            progressDialog.dismiss();
                            startActivity(changepassword);
                        }

                    }
                    Log.d("message  csdkhds", "" + message);
                    Log.d("phonre :  ", " " + phone);
                }

                @Override
                public void onFailure(Call<VerifyOTPResponse> call, Throwable t) {

                }
            });
        }
    });
}

我的界面: -

@POST("generateOTP")
    Call<GenerateOTPResponse> generateOTP(@Body GenerateOTPRequest generateOTPRequest);

    @POST("verifyOTP")
    Call<VerifyOTPResponse> verifyOTP(@Body VerifyOTPRequest verifyOTPRequest);

4 个答案:

答案 0 :(得分:1)

只需使用注释:

public interface Service {  
@Headers("application-Key", your key)
@GET("/example")
Call<List<Example>> getExamples();
}

所有示例均可在此处获取:https://futurestud.io/tutorials/retrofit-add-custom-request-header

答案 1 :(得分:0)

您可以在api方法中使用@Header注释,因为文档中已明确说明https://square.github.io/retrofit/

  

@Headers(“XYZ:value”)

答案 2 :(得分:0)

您可以在基础改造文件

中进行设置
request = original.newBuilder()
                            .header("header key", "your header)
                            .header("x-requested-with", "XMLHttpRequest")
                            .method(original.method(), original.body())
                            .build();

                    okhttp3.Response response = chain.proceed(request);

答案 3 :(得分:0)

@Header

这是特定于翻新的批注,它将使您可以将请求标头传递到目标HTTP端点,其中每个参数都代表一个请求标头条目。