如何将JSONObject发送到Android的Retrofit API中 [英] How to send a JSONObject into a Retrofit API call Android

查看:73
本文介绍了如何将JSONObject发送到Android的Retrofit API中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Android代码中首次实现了Retrofit,并且遇到了以下问题:

I have implemented the first time Retrofit in my Android code and am facing the following issues:

java.lang.IllegalArgumentException:@Body参数不能与形式或多部分编码一起使用.(参数1)

java.lang.IllegalArgumentException: @Body parameters cannot be used with form or multi-part encoding. (parameter #1)

我已经实现了如下代码:

I have implemented my code like below:

public interface APIService {
    @FormUrlEncoded
    @POST("/")
    @Headers({
        "domecode: axys",
        "Content-Type: application/json;charset=UTF-8"
    })
    Call<JsonObject> sendLocation(@Body JsonObject jsonObject);
}


public class ApiUtils {

    static String tempUrl = "http://192.168.16.114:8092/api/v1/location/tsa/";
    public static APIService getAPIService() {

        return RetrofitClient.getClient(tempUrl).create(APIService.class);
    }
}

public class RetrofitClient {

    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        if(retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

}

将值传递给API调用

JsonObject postParam = new JsonObject();
try {
    postParam.addProperty(Fields.ID, "asdf");
}

Call<JsonObject> call = apiService.sendLocation(postParam);
call.enqueue(
    new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            Log.d("response", "Getting response from server: " + response);
        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            Log.d("response", "Getting response from server: " + t);
        }
    }
);

推荐答案

您正在使用Android内部JSON API.您需要改用Gson的类.

You are using the Android internal JSON APIs. You need to use Gson's classes instead.

Call<JsonObject> sendLocation(@Body JsonObject jsonObject);

因此导入语句

import com.google.gson.JsonObject;

另一个错误是将回调作为参数传递给请求

Another error is passing the Callback as a parameter to the request

Call<JsonObject> call = apiService.sendLocation(jsonObject);
call.enqueue(new Callback<JsonObject>() {
   @Override
   public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
      Log.d("response", "Getting response from server: "+response);
   }

   @Override
   public void onFailure(Call<JsonObject> call, Throwable t) {
      Log.d("response", "Getting response from server: " + t);
   }
});

这篇关于如何将JSONObject发送到Android的Retrofit API中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆