[英]How to pass parameters to POST request in Retrofit - Android
[英]How to convert POST curl request to Retrofit Request in Android?
我正在嘗試使用 Retrofit 在 android 中表示以下 curl 請求,
curl -i -X POST \
https://graph.facebook.com/v13.0/1234567890/messages \
-H 'Authorization: Bearer ucuzZCQv9qb--token--0UMHaEhLwvuOW6WvapUGuPAkrDchj' \
-H 'Content-Type: application/json' \
-d '{ "messaging_product": "whatsapp", "to": "9477number", "type": "template", "template": { "name": "hello_world", "language": { "code": "en_US" } } }'
我的 API 客服 class
public interface APIService {
@POST("{phoneNoId}/messages")
Call<MsgResponse> SendMsg(@Path("phoneNoId") String phoneNoId,
@Header("Authorization") String authorization,
@Header("Content-Type") String types,
@Body String msgObj
);
}
我的 API 在 MainActivity.class 調用的地方
APIService apiService=RetroInstance.getRetrofitClient().create(APIService.class);
Call<MsgResponse> call=apiService.SendMsg("100798385993185",
"Bearer 5iWIZBiI5vogoNZBKbBJ0oZAibvZBG---token--xIcDPoW",
"application/json",
jsonBody
);
Log.d(TAG, "onCreate: "+call.toString());
call.enqueue(new Callback<MsgResponse>() {
@Override
public void onResponse(Call<MsgResponse> call, Response<MsgResponse> response) {
Log.d(TAG, "onResponse: "+response.toString());
}
@Override
public void onFailure(Call<MsgResponse> call, Throwable t) {
Log.d(TAG, "onFailure: "+t.getMessage());
Log.d(TAG, "onFailure: "+t.getStackTrace().toString());
}
});
在這里jsonbody
我正在使用 gson 得到 json object 如下所示String jsonBody=gson.toJson(msgObj);
我的請求成功,但我在下面收到 400 錯誤代碼錯誤消息,這里出了什么問題,謝謝
onResponse: Response{protocol=h2, code=400, message=, url=https://graph.facebook.com/v12.0/1234567890/messages}
您可以使用Interceptor
將標頭傳遞給您的Retrofit
請求。 這可能不是一個完美的方法,但它工作得很好,這些標頭隨每個 API 請求一起發送。
首先,擴展Interceptor
並將 header 添加到請求中,如下所示:
class LoggingInterceptor implements Interceptor {
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
Request newRequest = request.newBuilder()
.header("Authorization","YOUR AUTH CODE HERE")
.header("Content-Type","application/json").build();
return chain.proceed(newRequest);
}
}
現在您可以將此自定義攔截器與 OkHttpClient 一起使用:
OkHttpClientBuilder builder = OkHttpClient.Builder()
.addInterceptor(new MyInterceptor());
在構建 Retrofit object 時使用此客戶端:
Retrofit.Builder()
.baseUrl(YOUR_BASE_URL)
.client(okHttpClientBuilder.build())
.build()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.