如何在retrofit 1.9 API中传递头文件

时间:2017-06-23 09:57:41

标签: android web-services retrofit

规定─>

使用GET请求获取对象列表:

传递请求标头:

X-ACCESS-TOKEN =成功登录后收到的令牌

X-USER-EMAIL =登录时使用的电子邮件。

我正在使用此代码登录 - >

private void normalLoginToServer() {
    final ProgressDialog progressDialog = GeneralUtil.createProgressDialog(this, "Logging into app..");
    progressDialog.show();

Instead of using JSONObject, i need to pass Request Headers.
in a below Astrike code. how to pass Headers.? please help me.

    ***JSONObject outer_body = new JSONObject();
    JSONObject body = new JSONObject();
    try {
        body.put(Constants.USER_EMAIL, _emailText.getText().toString().trim());
        body.put(Constants.USER_PWD, _passwordText.getText().toString().trim());

        outer_body.put(Constants.USER, body);***

        try {
            TypedInput typedInput = new TypedByteArray("text/plain", outer_body.toString().getBytes("UTF-8"));

            apiService.loginToServer(typedInput, new Callback<UserInfo>() {
                @Override
                public void success(UserInfo response, Response response2) {
                    int status = response2.getStatus();
                    switch (status) {
                        case 200:
                            if (progressDialog.isShowing())
                                progressDialog.dismiss();
                            if (response == null)
                                return;
                            String status1 = response.getStatus();
                            if (status1.equalsIgnoreCase("success")) {
                                Toast.makeText(context, "Successful login", Toast.LENGTH_SHORT).show();
                                Data data = response.getData();
                                User user = data.getUser();
                                String token = user.getAccess_token();

                                Intent intent = new Intent(context, MainActivity.class);
                                intent.putExtra(Constants.ACCESS_TOKEN, token);
                                startActivity(intent);
                                finish();
                            } else if (status1.contains("failure")) {
                                Toast.makeText(context, "Username not found", Toast.LENGTH_SHORT).show();
                            }
                            break;

                        case 500:
                            Toast.makeText(context, getResources().getString(R.string.server_error), Toast.LENGTH_SHORT).show();
                            break;
                    }
                }

                @Override
                public void failure(RetrofitError retrofitError) {
                    if (progressDialog.isShowing())
                        progressDialog.dismiss();
                    if (retrofitError != null) {
                        if (retrofitError.getKind() != null) {
                            if (retrofitError.getKind().equals(RetrofitError.Kind.NETWORK)) {
                                Toast.makeText(context, "Check your network connection and try again later",
                                        Toast.LENGTH_SHORT).show();
                            }
                        } else if (retrofitError.getResponse() != null) {
                            if (retrofitError.getResponse().getStatus() == 500) {
                                Toast.makeText(context, getResources().getString(R.string.server_error), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }

            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

感谢Advenced。!!

2 个答案:

答案 0 :(得分:1)

您可以在改装api界面中使用@Header。例如,像:

void loginToServer(@Header("your_header") String yourHeaderValue, Callback<UserInfo> callback);

答案 1 :(得分:1)

假设您想要传递静态标头(那些为单个请求赢得更改的人)。 例如,此代码将缓存控制标头添加到/ tasks请求

public interface UserService {  
    @Headers("Cache-Control: max-age=640000")
    @GET("/tasks")
    List<Task> getTasks();
}

如果您需要传递动态标头(那些更改个别请求)

public interface UserService {  
    @GET("/tasks")
    List<Task> getTasks(@Header("Content-Range") String contentRange);
}

更多关于Retrofit Add Custom Request Header