繁体   English   中英

改造 2 - 获得 200 响应但未获得数据返回

[英]Retrofit 2 - Getting 200 response but not getting data returned

TL; 博士


新的改造所以这可能是一个菜鸟错误。 端点在邮递员中工作正常,我在Response{protocol=http/1.1, code=200, message=OK, url=http://192.168.1.249/api/v1/user/1}得到Response{protocol=http/1.1, code=200, message=OK, url=http://192.168.1.249/api/v1/user/1}但没有与用户。

问题


我使用 Laravel 构建了一个 REST API,我想从设备访问它。 将有许多端点需要访问,但我无法让它们中的任何一个工作。 我试图在添加其余部分之前让一个工作正常工作,但即使我得到 200 我也没有得到任何数据。

所有属性都存在于 response.body 中,但它们都为空。

守则


主活动.java

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;


import com.x.tools.actualrest.rest.User;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends Activity {

    private CdenApi cdenAPI;

    private String token;

    String requested_with = "XMLHttpRequest";
    String content_type = "application/json";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        createCdenAPI();

        cdenAPI.getUser(requested_with, content_type, "1").enqueue(userCallback);


    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void createCdenAPI() {
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(CdenApi.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        cdenAPI = retrofit.create(CdenApi.class);
    }

    Callback<User> userCallback = new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            if (response.isSuccessful()) {
                User data = new User();
                data = response.body();
            } else {

            }
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
            t.printStackTrace();
        }
    };
} 

CdenApi.java

import com.x.tools.actualrest.rest.User;

import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Path;
import retrofit2.Call;

public interface CdenApi {

    String BASE_URL = "http://192.168.1.249/api/v1/";

    @GET("user/{id}")
    Call<User> getUser(@Header("X-Requested-With") String req_with, @Header("Content-Type") String cont_type, @Path("id")String userId);

} 

用户.java

import com.google.gson.annotations.SerializedName;

public class User {

    @SerializedName("id")
    public Integer id;
    @SerializedName("name")
    public String name;
    @SerializedName("email")
    public String email;
    @SerializedName("access_level")
    public Integer accessLevel;
    @SerializedName("created_at")
    public String createdAt;
    @SerializedName("updated_at")
    public String updatedAt;
    @SerializedName("view_boxes")
    public ViewBoxes viewBoxes;

}

用户结果.java

import com.google.gson.annotations.SerializedName;

public class UserResult {

    @SerializedName("msg")
    public String msg;
    @SerializedName("user")
    public User user;

}

视图框.java

import com.google.gson.annotations.SerializedName;

public class ViewBoxes {

    @SerializedName("href")
    public String href;
    @SerializedName("method")
    public String method;

}

来自端点的 JSON:

{
    "msg": "User information",
    "user": {
        "id": 1,
        "name": "Guy",
        "email": "guy@ganker.com",
        "access_level": 1,
        "created_at": "2017-08-22 15:53:06",
        "updated_at": "2017-08-22 15:53:06",
        "view_boxes": {
            "href": "api/v1/user/1",
            "method": "GET"
        }
    }
}

解决方案


我需要知道我哪里出错了。 我是改造的新手,所以我确定我实施了一些错误,但我看不到问题。

在此先感谢您的帮助。

我认为问题在于你有Call<User> ,但是对于你的 json 你在服务器的响应中得到 UserResult,所以它必须是Call<UserResult>并且在 userCallback 中是相同的,而不是

Callback<User> userCallback = new Callback<User>

一定是

Callback<UserResult> userCallback = new Callback<UserResult>

和 onresponse 相同

public void onResponse(Call<UserResult> call, Response<UserResult> response) {
            if (response.isSuccessful()) {
                User data = new User();
                data = response.body().user;
            } else {

            }
        }

尝试这样做

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    createCdenAPI();
    Response<User> response = cdenAPI.getUser(requested_with, content_type, "1").execute();

    User user = response.body();
 }

在你的MainActivity.java

移除

User data = new User();
data = response.body();

并将其替换为

User data = response.body();

关于模型类,您可以尝试对网络、视图和数据库访问使用相同的模型类,但每个类都有一些怪癖,因此最好有一个通用模型类,可以将 db 和网络模型转换为/从。

关于房间和改造。 Room 似乎不喜欢孩子的列表,如果改造得到 200(成功)错误代码但没有数据,问题可能是转换过程失败并且改造不会给你任何信息。

尝试直接从 json 重新生成网络模型类并使用它们。 Android Studio 插件 JsonToKotlinClass 创建数据类 ALT-K 或右键单击 package -> New -> Kotlin data class from JSON

        @GET("/users")
        Call<ResponseBody> listRepos();//function to call api
    }

    RetrofitService service = retrofit.create(RetrofitService.class);
    Call<ResponseBody> result = service.listRepos(username);
    result.enqueue(new Callback<ResponseBody>() {

    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());//convert reponse to string
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});


response.body().string();

//you get this 

  {
    "msg": "User information",
    "user": {
        "id": 1,
        "name": "Guy",
        "email": "guy@ganker.com",
        "access_level": 1,
        "created_at": "2017-08-22 15:53:06",
        "updated_at": "2017-08-22 15:53:06",
        "view_boxes": {
            "href": "api/v1/user/1",
            "method": "GET"
        }
    }


//instead of this
 
Response{protocol=http/1.1,
 code=200, 
message=OK, 
url=http://192.168.1.249/api/v1/user/1}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM