1

I am trying to implement sendOTP of MSG91.There I have to API ,one for generating otp and another one for verifying otp.But there in post reuest I have to set a header ,so how can I set header in retrofit.I am attaching a pic of what to do.Please help me.enter image description here

post request:-

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;
    }
}

Response:-

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;
    }
}

my main activity:-

@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) {

                }
            });
        }
    });
}

my interface:-

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

    @POST("verifyOTP")
    Call<VerifyOTPResponse> verifyOTP(@Body VerifyOTPRequest verifyOTPRequest);
dhananjay sharma
  • 17
  • 1
  • 1
  • 5

4 Answers4

2

Just use annotation:

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

All examples are available here: https://futurestud.io/tutorials/retrofit-add-custom-request-header

K.Os
  • 5,123
  • 8
  • 40
  • 95
  • but where to call this – dhananjay sharma Jul 15 '17 at 10:34
  • You must define an interface like here, with specific endpoint provided in @GET annotation that you want to fetch data and then just make it like i suggested here. – K.Os Jul 15 '17 at 10:37
  • please tell me where and how to use this – dhananjay sharma Jul 15 '17 at 10:37
  • You did not provide code for the API class(final API service1), it should be done there and it should be an interface. See the simple examples that i provide link to. Eventually you can set the header in Retrofit builder like @Avinash suggested – K.Os Jul 15 '17 at 10:44
  • can u please tell me why am i getting null response in verification of otp by looking in the cod – dhananjay sharma Jul 16 '17 at 07:58
1

You can use @Header annotation for your api method as it is clearly stated in a documentation https://square.github.io/retrofit/

@Headers("XYZ: value")

Josef Adamcik
  • 5,620
  • 3
  • 36
  • 42
0

you can set it in your base retrofit file

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);
Avinash
  • 264
  • 5
  • 15
0

@Header

this is a Retrofit specific annotation which will allow you the pass the request headers to the targeting HTTP endpoint, where every argument represents a request header entry.