【发布时间】:2020-06-22 10:42:50
【问题描述】:
我尝试对 API 端点进行改造调用,但它返回了 400 error,但我的 curl 请求运行良好。我似乎无法发现错误,有人可以仔细检查我的工作,看看我哪里出错了吗?
有效的 curl 调用:
curl --request POST https://connect.squareupsandbox.com/v2/payments \
--header "Content-Type: application/json" \
--header "Authorization: Bearer accesstoken112233" \
--header "Accept: application/json" \
--data '{
"idempotency_key": "ab2a118d-53e2-47c6-88e2-8c48cb09bf9b",
"amount_money": {
"amount": 100,
"currency": "USD"},
"source_id": "cnon:CBASEITjGLBON1y5od2lsdxSPxQ"}'
我的改造电话:
public interface IMakePayment {
@Headers({
"Accept: application/json",
"Content-Type: application/json",
"Authorization: Bearer accesstoken112233"
})
@POST(".")
Call<Void> listRepos(@Body DataDto dataDto);
}
DataDto 类:
public class DataDto {
private String idempotency_key;
private String amount_money;
private String source_id;
public DataDto(String idempotency_key, String amount_money, String source_id) {
this.idempotency_key = idempotency_key;
this.amount_money = amount_money;
this.source_id = source_id;
}
}
最后拨打改造电话:
DataDto dataDto = new DataDto("ab2a118d-53e2-47c6-88e2-8c48cb09bf9b", "{\"amount\": 100, \"currency\": \"USD\"}", "cnon:CBASEITjGLBON1y5od2lsdxSPxQ");
RetrofitInterfaces.IMakePayment service = RetrofitClientInstance.getRetrofitInstance().create(RetrofitInterfaces.IMakePayment.class);
Call<Void> call = service.listRepos(dataDto);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) {
Log.d(TAG, "onResponse: " + response.toString());
}
@Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Log.d(TAG, "onFailure: Error: " + t);
}
});
改造实例:
public class RetrofitClientInstance {
private static Retrofit retrofit;
private static final String BASE_URL = "https://connect.squareupsandbox.com/v2/payments/";
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
编辑 1:将第二个参数更改为 JSON 对象
JSONObject jsonObject = new JSONObject();
try{
jsonObject.put("amount", 100);
jsonObject.put("currency", "USD");
}catch (Exception e){
Log.d(TAG, "onCreate: " + e);
}
DataDto dataDto = new DataDto("ab2a118d-53e2-47c6-88e2-8c48cb09bf9b", jsonObject, "cnon:CBASEITjGLBON1y5od2lsdxSPxQ");
【问题讨论】:
-
amount_money看起来像一个对象,但您将其视为字符串?可能是一个潜在的错误。 -
我不喜欢你的
@Post(".")。那是对的吗?如果它不起作用,那么错误消息是什么? -
@GV_FiQst (".") 很好 github.com/square/retrofit/issues/1701 我只是收到 400 错误。并且根据他们的 API 400 是无效参数?
-
您能分享一下您设置改造实例的方式吗?
-
是的,我在上面的编辑中添加了