【问题标题】:post request with retrofit gets responce a s bad request in androidpost request with retrofit get response a s bad request in android
【发布时间】:2020-07-07 13:08:51
【问题描述】:

我正在使用https://docs.ngenius-payments.com/reference#hosted-payment-page在android中付款

标题: 将这些标头添加到您的请求中(请注意,您应该将“your_api_key”替换为“入门”部分中的服务帐户 API 密钥)。

标题值 Content-Type application/vnd.ni-identity.v1+json

基本授权:your_api_key

正文/表格数据: 将以下信息添加到请求的表单/正文内容中。

示例请求(正文): JSON { ‘realmName’:‘你’ }

这些是标题和内容类型,我使用改造创建了一个发布方法

   public static Retrofit getRetrofitClient() {
    //If condition to ensure we don't create multiple retrofit instances in a single application
    if (retrofit == null) {
        //Defining the Retrofit using Builder
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL) //This is the only mandatory call on Builder object.
                .addConverterFactory(GsonConverterFactory.create()) // Convertor library used to convert response into POJO
                .build();
    }
    return retrofit;

}

我的api接口是

@POST("identity/auth/access-token")
Call<NgeniusPaymentAccessTokenModel> nGeniusAccessToken(@Header("content-type") String ContentType, @Header("authorization") String apiKey, @Body JsonObject object);

我叫它

    JsonObject postParam = new JsonObject();
        try {
            postParam.addProperty("realmName", "ni");
        } catch (Exception e) {
            e.printStackTrace();
        }
 Call call = apiService.nGeniusAccessToken(contentType, "Basic "+apiKey, postParam);

我得到的响应是错误,告诉它一个错误的请求,如何解决这个问题

【问题讨论】:

  • 您发送的请求正文不符合您后端的预期格式。请清除请求正文要求。

标签: android post http-headers retrofit


【解决方案1】:

你可以试试下面的代码:

String contentType = "application/vnd.ni-identity.v1+json";
String authorization = "Basic: "+apiKey;
JSONObject postParam = new JSONObject();
        try {
            postParam.put("realmName", "ni");
        } catch (JSONException e) {
            e.printStackTrace();
        }
 Call call = apiService.nGeniusAccessToken(contentType, authorization, postParam);

【讨论】:

  • 你的“不工作”是什么意思你能解释一下@jin
【解决方案2】:

这个对我有用,我将所有标题放在标题映射中

创建地图

Map<String, String> stringMap = new HashMap<>();
    try {
        stringMap.put("Authorization", "auth");
        stringMap.put("Content-Type", "CONTENT_TYPE");
        stringMap.put("accept", "accept");
    } catch (Exception e) {
        e.printStackTrace();
    }

api接口长这样

@POST("transactions/orders")
Call<ResponseBody> nCreateOrder(@HeaderMap Map<String, String> headers,String out, @Body JsonObject object);

现在调用它

 nCreateOrder(stringMap ,"out",jsonObject);

【讨论】:

    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多