Android Retrofit动态设置标头值

时间:2017-02-21 07:46:38

标签: android header retrofit

我有一个Android应用程序,其中图像上传到服务器。我正在使用改造库来上传图像。为此,有一个标题部分,它是一个access_token,在调用时动态添加。

ApiInterface

    @Headers({"source: android"})
    @Multipart
    @POST("doImageUpload.php")
    Call<ResponseBody> imageUpload(@Header("access_token") String accesstoken,@Part("username") RequestBody  username, @Part("action") RequestBody  action,@Part("image_data") RequestBody  image_data  );

ImageUpload功能

public void imageupload(String imagepath)
{

    final ProgressDialog mProgressDialog = new ProgressDialog(this);
    mProgressDialog.setIndeterminate(true);
    mProgressDialog.setMessage("Loading...");
    mProgressDialog.show();
    String action = "imageUpload";

    String access = mPreferences.getString("accesstoken","");
    ApiInterface apiService =
            ApiClient.getClient().create(ApiInterface.class);
    final String TAG = "Image Upload";

    MediaType type = MediaType.parse("text/plain; charset=utf-8");


    Call<ResponseBody> call = apiService.imageUpload(@Header(RequestBody.create(type,mPreferences.getString("accesstoken", "")))
            RequestBody.create(type,mPreferences.getString("UserName", "")),RequestBody.create(type,imagepath),RequestBody.create(type,action));

    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody>call, Response<ResponseBody> response) {
            ResponseBody ResponseBody = response.body();
            Log.d("requrl",response.raw().request().url().toString());
            Log.d(TAG, "signup" + ResponseBody.toString());


            if (mProgressDialog.isShowing())
                mProgressDialog.dismiss();

            try {

                JSONObject obj = new JSONObject(response.body().string());

                Log.d("chkva","--"+obj.getBoolean("status"));


                }


            } catch (Exception exception){

                Log.d("Error123","sad"+exception.getMessage());

            }

        }

        @Override
        public void onFailure(Call<ResponseBody>call, Throwable t) {
            // Log error here since request failed
            Log.e(TAG, t.toString());
        }
    });

}

我的access_token存储在共享首选项中,我必须将此access_token添加到图像上传功能。我不知道我是否使用正确的方法添加标题。在这种情况下,有人可以帮助我。

提前谢谢

1 个答案:

答案 0 :(得分:1)

imageUpload()中的参数标题类型为STRING,您只需填写一个String标题。

Call<ResponseBody> call = apiService.imageUpload(mPreferences.getString("accesstoken", ""), 
            RequestBody.create(type,mPreferences.getString("UserName", "")),RequestBody.create(type,imagepath), RequestBody.create(type,action));