如何使用 Retrofit 库将 X-API-Key 和 X-Session 添加到 header?

How to add X-API-Key and X-Session to header using Retrofit library?

我想使用 Retrofit 库而不是 HttpURLConnection 我的 multipart request 将图像发送到服务器。我的 HttpURLConnection 请求由于某种原因无法正常工作。

但我在 Retrofit 中遇到问题,我不知道如何将 Session tokenAPI key 添加到我的请求中。

这是我对 HttpURLConnection 的每个请求使用的解决方案(它适用于除多部分请求之外的所有内容):

val con = url.openConnection() as HttpURLConnection
con.apply {
    requestMethod = method
    useCaches = false
    doOutput = true
    doInput = true
    addRequestProperty(HEADER_CONNECTION, "Keep-Alive")
    addRequestProperty(HEADER_CACHE_CONTROL, "no-cache")
    addRequestProperty(HEADER_CONTENT_TYPE, "multipart/form-data")
    addRequestProperty("X-API-Key", apiType.apiKey)
    addRequestProperty("X-Session", getServerSession())
}

这是我使用 Retrofit 库的请求:

val f = File(app.cacheDir, filename)
f.createNewFile()

val fos = FileOutputStream(f)
fos.write(data)
fos.flush()
fos.close()

val reqFile = RequestBody.create(MediaType.parse("image/*"), f)
val body = MultipartBody.Part.createFormData("upload", f.name, reqFile)

val httpUrl = HttpUrl.Builder()
    .scheme("https")
    .host(mainUrl)
    .addPathSegment(apiSegment)
    .addQueryParameter("X-API-Key", apiType.apiKey)
    .addQueryParameter("X-Session", getServerSession())

val service = Retrofit.Builder().baseUrl(httpUrl.build()).build().create(Service::class.java)
val req = service.postImage(body)
val response = req.execute()

我使用了 addQueryParameter,因为我读到这是将这两个参数添加到 header 的方式,但这只会影响我的 URL for API 调用,它会添加 API Key 和 Session 到 URL,服务器根本无法识别。

更新:

我的 Post 服务界面:

internal interface MultipartService {
        @Multipart
        @POST("{url}")
        fun postImage(@Part image: MultipartBody.Part): Call<ResponseBody>
        fun setEndpoint(@Path("url") endpoint: String): Call<ResponseBody>
    }

更新:已修复

   internal interface MultipartServicePost {
        @POST("{url}")
        @Multipart
        fun postImage(@Part image: MultipartBody.Part, @Path(value = "url", encoded = true) endpoint: String): Call<ResponseBody>
    }

addQueryParameter()顾名思义就是在Query中添加参数。

你想要的是 Interceptor。这是一个例子:

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("X-API-Key", apiType.apiKey)
            .header("X-Session", getServerSession())
            .method(original.method(), original.body())
            .build();

        return chain.proceed(request);
    }
}

关于动态url,您可以在定义界面时定义动态路径段。示例:

public interface PostService {  

    @GET("/posts/{post_id}")
    Task getPost(@Path("post_id") long id);
}