添加授权头接口android改造

时间:2018-07-24 09:04:22

标签: android client-server retrofit retrofit2

我正在使用改造库来解决与服务器请求有关的任务。我从服务器开发人员那里得到了参数:

URL
https://server/v1/message/list
Edit this section
Method
GET
Edit this section
HTTP Headers
Authorization:Bearer $access_token
Edit this section
URL Params
type 
0 - for received messages
1 - for sent messages
Optional:

offset 
In normal case you should not pass this parameter manually. It uses in previous/next urls, nevertheless it can takes values > 1 for getting offset messages list.

Edit this section
Data Params
{}
Edit this section
Success Response
HTTP 200
{
    "count": int, # number of messages 
    "messages": [ # array of messages
        {
            "id": int, # message id
            "subject": str, # message subject
            "can_delete": int, # can it be deleted (1) or not (0)
            "new": int # message already read (0) or not (1)
            "date": str, # date of message in 'd.m.y'. If message was sent today format will be 'H:M'
            "receiver_name": str, # name of receiver if type=1
            "sender_name": str, # name of sender if type=0
        }, ...
    ],
    "next_url": URL,  # url for get next messages, if no more messages value is null
    "previous_url": URL # url for get previous messages, if no more messages value is null
}

这是我的代码:

@Headers("Content-type: application/json")
    @GET("/v1/message/list")
    Call<List<MessageINAnswer>> getInMess();

我有请求类:

public class MessageIN {
    @SerializedName("subject")
    private String subject;
    @SerializedName("date")
    private String date;
    @SerializedName("sender_name")
    private String sender_name;
    @SerializedName("receiver_name")
    private String receiver_name;

    public MessageIN(String sender_name, String date, String receiver_name, String subject) {
        this.sender_name = sender_name;
        this.date = date;
        this.receiver_name = receiver_name;
        this.subject = subject;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getSender_name() {
        return sender_name;
    }

    public void setSender_name(String sender_name) {
        this.sender_name = sender_name;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getReceiver_name() {
        return receiver_name;
    }

    public void setReceiver_name(String receiver_name) {
        this.receiver_name = receiver_name;
    }
}

毕竟,我正在尝试在mainactivity类中初始化我的接口和类:

 public void info() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://server/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        APIService mAPIService = retrofit.create(APIService.class);
        Call<List<MessageIN>> listCall = mAPIService.getInMess();
        listCall.enqueue(new Callback<List<MessageIN>>() {
            @Override
            public void onResponse(@NonNull Call<List<MessageIN>> call, @NonNull Response<List<MessageIN>> response) {

            }

            @Override
            public void onFailure(@NonNull Call<List<MessageIN>> call, @NonNull Throwable t) {

            }
        });
    }

现在我从服务器收到失败消息,该消息说未提供授权标头。也许我的代码或开发策略有一些错误。希望您能帮助我解决以下问题。

P.S。对不起,我的英语:))

1 个答案:

答案 0 :(得分:2)

使用此类并根据需要在addHeader()方法中添加标头。

public class ApiClient {

    private static Retrofit retrofit;
        public static Retrofit addHeader() {
            OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                    .connectTimeout(40, TimeUnit.SECONDS)
                    .readTimeout(40, TimeUnit.SECONDS)
                    .writeTimeout(40, TimeUnit.SECONDS)
                    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(Interceptor.Chain chain) throws IOException {
                            Request original = chain.request();
                            Request request = original.newBuilder()
                                    .header("Key", "Value")
                                    .header("Key", "Value")
                                    .method(original.method(), original.body())
                                    .build();

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

            retrofit = new Retrofit.Builder()
                    .baseUrl("Your Base Url")
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(okHttpClient)
                    .build();
            return retrofit;
        }
}

并在您的活动或片段中像这样使用它

APIService mAPIService = ApiClient.addHeader().create(APIService.class);
Call<List<MessageIN>> listCall = mAPIService.getInMess();
    listCall.enqueue(new Callback<List<MessageIN>>() {
        @Override
        public void onResponse(@NonNull Call<List<MessageIN>> call, @NonNull Response<List<MessageIN>> response) {

        }

        @Override
        public void onFailure(@NonNull Call<List<MessageIN>> call, @NonNull Throwable t) {

        }
    });