我正在嘗試使用 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 服務類
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
);
}
我在 MainActivity.class 中的 API 呼叫位置
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 物件,如下所示String jsonBody=gson.toJson(msgObj);
我的請求成功,但我在下面收到 400 錯誤代碼錯誤訊息,這里出了什么問題,謝謝
onResponse: Response{protocol=h2, code=400, message=, url=https://graph.facebook.com/v12.0/1234567890/messages}

uj5u.com熱心網友回復:
您可以Retrofit使用 將標頭傳遞給您的請求Interceptor。這可能不是一個完美的方法,但效果很好,這些標頭隨每個 API 請求一起發送。
首先,擴展Interceptor請求頭并將其添加到請求中,如下所示:
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 物件時使用此客戶端:
Retrofit.Builder()
.baseUrl(YOUR_BASE_URL)
.client(okHttpClientBuilder.build())
.build()
uj5u.com熱心網友回復:
一切都在這個視頻中得到了很好的解釋,
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/489585.html
標籤:爪哇 安卓 卷曲 facebook-graph-api 改造2
上一篇:從ec2實體提交curl命令不會發送附加安全組態檔的憑據
下一篇:如何正確決議curl中的yml?
