【问题标题】:Retrofit getting response null @post method改造得到响应 null @post 方法
【发布时间】:2017-08-19 11:22:29
【问题描述】:

实际上,在 Retrofit 中,我正在尝试传递参数并且期待输出。 但在这里它显示响应为空。这是我正在尝试但不起作用的代码:

APIClient.java

class APIClient {

public static final String BASE_URL = "http://xxxxxxx:xxxx/";
private static Retrofit retrofit = null;

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

MainActivity.java

public class MainActivity extends AppCompatActivity implements ListView.OnItemClickListener {

//Root URL of our web service

//Strings to bind with intent will be used to send data to other activity
public static final String KEY_company_ID = "org_video";
public static final String KEY_news_NAME = "category_name";
public static final String KEY_likes_PRICE = "file_size";
public static final String KEY_url_image = "org_thumbnail";

Button mCheck;
//List view to show data
private ListView listView;
private View parentView;
//List of type books this list will store type Book which is our data model
private List<Company> companys;
private CompanyAdapter adapter;
CompanyAPI apiInterface;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mCheck = (Button)findViewById(R.id.btn);


    /**
     * Array List for Binding Data from JSON to this List
     */
   // companys = new ArrayList<>();

    parentView = findViewById(R.id.parentLayout);
    //Initializing the listview
    listView = (ListView) findViewById(R.id.listViewBooks);

    mCheck.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

                    loginRetrofit2Api("Onnet CMS");

        }
    });
    //Calling the method that will fetch data
   //getCompanyDetails();

    //Setting onItemClickListener to listview
    listView.setOnItemClickListener(this);
}

private void loginRetrofit2Api(String userId) {
    final Company comp = new Company(userId);

    apiInterface = APIClient.getClient().create(CompanyAPI.class);
    Log.e("apiInterface",""+apiInterface);
    Call<Company> call1 = apiInterface.getOutput("OnnetCMS");
    call1.enqueue(new Callback<Company>() {

        @Override
        public void onResponse(Call<Company> call, Response<Company> response) {
            Company loginResponse = response.body();

            Log.e("response", "Response 1 --> " + loginResponse);
            if (loginResponse != null) {
                Log.e("response", "getUserId          -->  " + loginResponse.getCompany());
                Log.e("response", "getFirstName       -->  " + loginResponse.getUrl());
                Log.e("response", "getLastName        -->  " + loginResponse.getName());
                Log.e("response", "getProfilePicture  -->  " + loginResponse.getNews());


            }
        }

        @Override
        public void onFailure(Call<Company> call, Throwable t) {
            Toast.makeText(getApplicationContext(), "onFailure called ", Toast.LENGTH_SHORT).show();
            call.cancel();
        }
    });
}

CompanyAPI.java

public interface CompanyAPI {

/*Retrofit get annotation with our URL
   And our method that will return us the list ob Book
*/
@FormUrlEncoded
@POST("/cms/contents/reqGetContentsInfoList.on")
Call<Company> getOutput(@Field("com_id") String comId);
}

回应:

{
    "result_msg": "SUCCESS",
    "content_list":
    [
        {
            "org_video": "iOT.mp4",
            "end_date": "2018-07-21 12:12:34.0",
            "file_path": "/var/www/html/contents/",
            "category_name": "E-learning",
            "enctrs_stat": 0,
            "cnt_id": 528,
            "auth": 99,
            "thumbnail_file": "http://106.51.64.251:180/contents/playVideo.png",
            "duration_sec": 0,
            "file_size": 91007457,
            "org_thumbnail": "http://106.51.64.251:180/contents/playVideo.png",
            "category_id": 176,
            "enable": 0,
            "hit_count": 0,
            "start_date": "2017-07-21 12:12:34.0"
        },
        {
            "org_video": "BigData.mp4",
            "end_date": "2018-07-21 10:48:12.0",
            "file_path": "/var/www/html/contents/",
            "category_name": "Demo",
            "enctrs_stat": 0,
            "cnt_id": 527,
            "auth": 99,
            "thumbnail_file": "http://106.51.64.251:180/contents/playVideo.png",
            "duration_sec": 0,
            "file_size": 3808501,
            "org_thumbnail": "http://106.51.64.251:180/contents/playVideo.png",
            "category_id": 198,
            "enable": 0,
            "hit_count": 0,
            "start_date": "2017-07-21 10:48:12.0"
        },
        {
            "org_video": "What is IoT-.mp4",
            "end_date": "2018-07-21 10:05:14.0",
            "file_path": "/var/www/html/contents/",
            "category_name": "E-learning",
            "enctrs_stat": 0,
            "cnt_id": 526,
            "auth": 99,
            "thumbnail_file": "http://106.51.64.251:180/contents/playVideo.png",
            "duration_sec": 0,
            "file_size": 10455459,
            "org_thumbnail": "http://106.51.64.251:180/contents/playVideo.png",
            "category_id": 176,
            "enable": 0,
            "hit_count": 0,
            "start_date": "2017-07-21 10:05:14.0"
        },
        {
            "org_video": "IoT-Prelims Current Affairs.mp4",
            "end_date": "2018-07-21 09:54:44.0",
            "file_path": "/var/www/html/contents/",
            "category_name": "E-learning",
            "enctrs_stat": 0,
            "cnt_id": 523,
            "auth": 99,
            "thumbnail_file": "http://106.51.64.251:180/contents/playVideo.png",
            "duration_sec": 0,
            "file_size": 8134193,
            "org_thumbnail": "http://106.51.64.251:180/contents/playVideo.png",
            "category_id": 176,
            "enable": 0,
            "hit_count": 0,
            "start_date": "2017-07-21 09:54:44.0"
        },
        {
            "org_video": "IoT-Architecture 4 Beginners.mp4",
            "end_date": "2018-07-21 09:47:06.0",
            "file_path": "/var/www/html/contents/",
            "category_name": "E-learning",
            "enctrs_stat": 0,
            "cnt_id": 522,
            "auth": 99,
            "thumbnail_file": "http://106.51.64.251:180/contents/playVideo.png",
            "duration_sec": 0,
            "file_size": 91007457,
            "org_thumbnail": "http://106.51.64.251:180/contents/playVideo.png",
            "category_id": 176,
            "enable": 0,
            "hit_count": 0,
            "start_date": "2017-07-21 09:47:06.0"
        },
        {
            "org_video": "Advantages of e-Learning.mp4",
            "end_date": "2018-07-21 09:43:05.0",
            "file_path": "/var/www/html/contents/",
            "category_name": "E-learning",
            "enctrs_stat": 0,
            "cnt_id": 521,
            "auth": 99,
            "thumbnail_file": "http://106.51.64.251:180/contents/playVideo.png",
            "duration_sec": 0,
            "file_size": 6022401,
            "org_thumbnail": "http://106.51.64.251:180/contents/playVideo.png",
            "category_id": 176,
            "enable": 0,
            "hit_count": 0,
            "start_date": "2017-07-21 09:43:05.0"
        },
        {
            "org_video": "6 Trends in E-learning.mp4",
            "end_date": "2018-07-21 09:42:55.0",
            "file_path": "/var/www/html/contents/",
            "category_name": "E-learning",
            "enctrs_stat": 0,
            "cnt_id": 520,
            "auth": 99,
            "thumbnail_file": "http://106.51.64.251:180/contents/playVideo.png",
            "duration_sec": 0,
            "file_size": 6152424,
            "org_thumbnail": "http://106.51.64.251:180/contents/playVideo.png",
            "category_id": 176,
            "enable": 0,
            "hit_count": 0,
            "start_date": "2017-07-21 09:42:55.0"
        }
    ],
    "result_code": "SG02S200"
}

这是我从 REST API 得到的响应。

Company.java

这是公司的模型类。

public class Company {

@SerializedName("org_video")
@Expose
private String company;
@SerializedName("category_name")
@Expose
private String news;
@SerializedName("file_size")
@Expose
private int likes;

@SerializedName("result_msg")
public String ResponseCode;
@SerializedName("category_id")
public String ResponseMessage;

public String getResponseCode() {
    return ResponseCode;
}

public void setResponseCode(String responseCode) {
    ResponseCode = responseCode;
}

public String getResponseMessage() {
    return ResponseMessage;
}

public void setResponseMessage(String responseMessage) {
    ResponseMessage = responseMessage;
}

@SerializedName("duration_sec")

@Expose
private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}

@SerializedName("org_thumbnail")
@Expose
private String url;

public String getCompany() {
    return company;
}

public void setCompany(String company) {
    this.company = company;
}

public String getNews() {
    return news;
}

public void setNews(String news) {
    this.news = news;
}

public int getLikes() {
    return likes;
}

public void setLikes(int likes) {
    this.likes = likes;

}

public Company(String name){
    this.name = name;
}
}

【问题讨论】:

  • 如果上面那个是调用api时的响应。那么loginResponse.getCompany() 的这一行是什么,'loginResponse.getUrl()'
  • 好的,但我没有正确重命名它们实际上我为另一个 api 尝试了相同的代码,所以我没有完全重命名。
  • 你能发布你的Company模型类
  • 是的,现在你检查我已经更新了。
  • 你正在使用 Gson 来解析它。所以你应该根据它制作你的模型类。稍等,我会发布模型类以供您回复。

标签: android rest retrofit2


【解决方案1】:

// 1. 创建如下所示的 ContentModel 类

public class ContentModel {

    @SerializedName("result_msg")
    public String result_msg;

    @SerializedName("org_video")
    public String org_video;

    @SerializedName("end_date")
    public String end_date;

    @SerializedName("file_path")
    public String file_path;

    @SerializedName("category_name")
    public String category_name;

    @SerializedName("enctrs_stat")
    public String enctrs_stat;

    @SerializedName("cnt_id")
    public int cnt_id;

    @SerializedName("auth")
    public int auth;

    @SerializedName("thumbnail_file")
    public String thumbnail_file;

    @SerializedName("duration_sec")
    public String duration_sec;

    @SerializedName("file_size")
    public String file_size;

    @SerializedName("org_thumbnail")
    public String org_thumbnail;

    @SerializedName("category_id")
    public int category_id;

    @SerializedName("enable")
    public String enable;

    @SerializedName("hit_count")
    public String hit_count;

    @SerializedName("start_date")
    public String start_date;

}

// 2. 创建如下所示的 ContentJsonModel 类

public class ContentJsonModel {

    @SerializedName("result_msg")
    public String result_msg;

    @SerializedName("content_list")
    public List<ContentModel> content_list;

    @SerializedName("result_code")
    public String result_code;
}

// 3. 设置 Rest API

public interface CompanyAPI {

/*Retrofit get annotation with our URL
   And our method that will return us the list ob Book
*/
@FormUrlEncoded
@POST("cms/contents/reqGetContentsInfoList.on")
Call<ContentJsonModel> getOutput(@Field("com_id") String comId);

}

// 现在终于在 Main Class 上调用它

private void loginRetrofit2Api(String userId) {

  Call<ContentJsonModel> call1 = APIClient.getClient().create(CompanyAPI.class).getOutput(userId);
    call1.enqueue(new Callback<ContentJsonModel>() {

        @Override
        public void onResponse(Call<ContentJsonModel> call, Response<ContentJsonModel> response) {

        // All the content_data will be stored in the list
            List<ContentModel> contentModel = response.body().content_list;

            //now you can get single values like this 
             for(ContentModel model : contentModel){


             }



        }

        @Override
        public void onFailure(Call<ContentJsonModel> call, Throwable t) {
            Toast.makeText(getApplicationContext(), "onFailure called ", Toast.LENGTH_SHORT).show();

       }
    });
}

【讨论】:

  • 但参数是这样的,{"com_id"="Onnet CMS"}。我尝试了您的回答,但仍然为空
  • / 在改造中并不重要。并且空间将在改造中被替换 %20。 square.github.io/retrofit/2.x/retrofit/retrofit2/http/…
  • 你有没有像@POST("cms/contents/reqGetContentsInfoList.on")一样打电话
  • 你检查过我更新的答案吗?如果它不起作用,那么您可以展示您的公司模型类
  • huhhh.. 您的模型类的主要问题是您从 Api 获得的响应与您的模型类不同
【解决方案2】:

您的 apiInterface 变量值是否与

CompanyAPI apiInterface = APIClient.getClient().create(CompanyAPI.class);

【讨论】:

  • 我没有完全理解。能否请您简要介绍一下
  • Call&lt;Company&gt; call1 = apiInterface.getOutput("Onnet CMS"); 行之前你需要 apiInterface 变量值
  • 当我调试它显示 apiInterface = retrofit2.Retrofit$1@2cfe93b0
  • 我是这样的,E/apiInterface:retrofit2.Retrofit$1@31480872
  • 在您的代码中添加CompanyAPI apiInterface = APIClient.getClient().create(CompanyAPI.class); 行后您得到它了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-15
  • 2018-06-05
  • 2016-01-09
  • 1970-01-01
  • 1970-01-01
  • 2020-09-12
  • 2017-01-28
相关资源
最近更新 更多