【问题标题】:Retrofit GET method error Non-body HTTP method cannot contain @Body改造 GET 方法错误 Non-body HTTP 方法不能包含 @Body
【发布时间】:2020-08-25 01:48:48
【问题描述】:

我是 Retrofit 的新手。我正在尝试使用基本 url 调用 api,但是在加载函数时出现错误。有一个对象,里面有两个不同的数组,名称为 animal 和 bird。我需要从对象调用这个数组并需要在 gridview 中加载适配器。 这就是我在片段中调用函数的方式。

 My error.

java.lang.IllegalArgumentException: Non-body HTTP method cannot contain @Body.
    for method GetDataService.getAll
  1. 这是我的 JSON 响应

    {
       "animals": [
       {
          "animalName": "String",
          "animalID": "integer",
    
    }
    
     ],
        "birds": [
      {
        "birdsId": "integer",
        "birdsname": "string
     }
    
    ],
    
     "ID": "integer"
    }
    
  2. 在片段中调用 GET

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://demoapp.in/")
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    
    GetDataService service = retrofit.create(GetDataService .class);
    Call<TableResponse> call= service.getAll(new TableResponse());
    call.enqueue(new Callback<TableResponse>() {
        @Override
        public void onResponse(Call<TableResponse> call, Response<TableResponse> response) {
    
            String passKey = response.body().getPassKey();
            List<Table> TableName = response.body().getTables();
            String[] TableNameArray = new String[TableName.size()];
            for (int i = 0; i < TableName.size(); i++) {
    
                TableNameArray[i] = TableName.get(i).getTableName();
    
            }
    
            gridView.setAdapter(new TableViewAdapter(getContext(), TableNameArray));
    
        }
    
        @Override
        public void onFailure(Call<TableResponse> call, Throwable t) {
    
        }
    });
    

3.TableResponse,这个文件中的java类是使用jsonschema2pojo生成的

@SerializedName("animal")
@Expose
private List<Table> animal = null;
   ......
  public TableResponse(){
    this.animal= animal;
    this.birds= birds;
    this.ID = ID;
   }


public List<Table> getTables() {
    return tables;
}

  -------

4.GetDataService.java

@GET("Animal.ashx")
Call<TableResponse> getAll(@Body TableResponse tableResponse);

【问题讨论】:

  • 您是否尝试将 Call getAll(@Body TableResponse tableResponse) 更改为 Call getAll()?
  • 当您将参数作为@Body 传递时,它不是 GET 的模板
  • @CôngHải while call this fumction Call getAll() 错误消失了,但它没有获取数据
  • 你的get api需要参数吗?
  • @sherin 使用 get 请求时不能有 body 有效负载,body 仅用于 Post/Put 请求

标签: android json api retrofit retrofit2


【解决方案1】:

@Headers("Content-Type: application/json")

@GET("helper-url")

fun getHelperUrl(

@Query("api_token") apiToken: String,

@Query("authtype") authType: String,

@Query("channel") channel: String

): Call&lt;ResponseHelperUrl&gt;

【讨论】:

猜你喜欢
  • 2016-10-22
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多