我试图进行POST Retrofit响应,但我必须从这个响应中获取数据。在堆栈中我发现请求没问题且代码== 200,但响应= 0.但是这个请求必须给我数据,我从Postman服务检查过这个。如何从我的请求中获取数据?
使用Postman的片段和结果进行堆栈跟踪:
response = {Response@830025479464}
body = {SignInResults@830025477808}
signInResult = null
signInResults = null
errorBody = null
rawResponse = {Response@830025473584} "Response{protocol=http/1.1, code=200, message=OK, url=https://api.vid.me/auth/create}"
body = {OkHttpCall$NoContentResponseBody@830025471872}
cacheControl = null
cacheResponse = null
request = {Request@830024580584} "Request{method=POST, url=https://api.vid.me/auth/create, tag=Request{method=POST, url=https://api.vid.me/auth/create, tag=null}}"
handshake = {Handshake@830025421608}
headers = {Headers@830025472832} "Access-Control-Allow-Headers: DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Content-Length,Authorization,AccessToken\nAccess-Control-Allow-Methods: GET, POST, OPTIONS, HEAD\nAccess-Control-Allow-Origin: *\nContent-Type: application/json\nDate: Tue, 26 Apr 2016 11:16:04 GMT\nServer: nginx\nSet-Cookie: rid=bbf4159793d4402caf449f8eeabe0404; expires=Sat, 17-May-2031 01:48:34 GMT; Max-Age=475079550; path=/; domain=vid.me\nSet-Cookie: srid=QYpbrONRvejA7DiwZIYTg-dgf8Ug-JBPIKnJL9u7coLmkK585aPsQyY; expires=Sat, 17-May-2031 01:48:34 GMT; Max-Age=475079550; path=/; domain=vid.me\nSet-Cookie: vmtoken=418bdb0823fd49729a51a6d82baf8521; expires=Wed, 26-Apr-2017 11:16:04 GMT; Max-Age=31536000; path=/; domain=vid.me; secure\nStrict-Transport-Security: max-age=31536000; includeSubdomains\nVary: Accept-Encoding\nX-Request-Time: 87\nX-Vidme-Authorization-Okay: false\nX-Vidme-Server-Id: 9610996701283818874f67e619e7c6ef\ntransfer-encoding: chunked\nConn"
message = "OK"
networkResponse = {Response@830025461696} "Response{protocol=http/1.1, code=200, message=OK, url=https://api.vid.me/auth/create}"
priorResponse = null
protocol = {Protocol@830023792880} "http/1.1"
code = 200
Postman的结果:
{
"status": true,
"auth": {
"token": "12f6d4123b9947e79f37a4c415bb4b51",
"expires": "2017-04-26 10:38:05",
"user_id": "11272862"
},
"user": {
"user_id": "11272862",
"username": "prozrostyslav",
"full_url": "https://vid.me/prozrostyslav",
"avatar": null,
"avatar_url": "https://d2ha22j8ys3e0o.cloudfront.net/images/default-avatars/13.png?602-2-2-4-9",
"cover": null,
"cover_url": "https://d2ha22j8ys3e0o.cloudfront.net/images/default-covers/03.jpg?602-2-2-4-9",
"displayname": null,
"follower_count": 0,
"likes_count": "0",
"video_count": 0,
"video_views": "0",
"videos_scores": 0,
"comments_scores": 0,
"bio": null
}
}
我的片段:
public class FeedFragment extends Fragment {
EditText username;
EditText password;
Button btnLogin;
public List<SignInResult> signInResult;
String username_value,password_value;
public static final String ROOT_URL = "https://api.vid.me/";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_feed, container, false);
username = (EditText) rootView.findViewById(R.id.user_name_field);
password = (EditText) rootView.findViewById(R.id.password_field);
btnLogin = (Button) rootView.findViewById(R.id.button_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Authorize();
}
});
return rootView;
}
public void Authorize() {
Retrofit retrofitAdapter = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ROOT_URL)
.build();
final VideoApi videoApi = retrofitAdapter.create(VideoApi.class);
username_value = username.getText().toString();
password_value = password.getText().toString();
String basicauth = "Basic "+ Base64.encodeToString(String.format("%s:%s",username_value,password_value).getBytes(),Base64.NO_WRAP);
Call<SignInResults> call = videoApi.insertUser(username_value,password_value);
call.enqueue(new Callback<SignInResults>() {
@Override
public void onResponse(Call<SignInResults> call, Response<SignInResults> response) {
int i = response.body().signInResult.getUser_id();
Log.d("Response ==>> ", String.valueOf(i));
}
@Override
public void onFailure(Call<SignInResults> call, Throwable t) {
}
});
}
}
SignInResult:
public class SignInResult {
@SerializedName("authorization")
@Expose
private String authorization;
@SerializedName("code")
@Expose
private String code;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@SerializedName("username")
@Expose
private String username;
@SerializedName("user_id")
@Expose
private Integer user_id;
public Integer getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
}
SignInResults:
public class SignInResults {
public SignInResult signInResult;
public List<SignInResult> getSignInResults() {
return signInResults;
}
List<SignInResult> signInResults;
}
API接口:
public interface VideoApi {
@GET("/videos/featured")
Call<Videos> getFeaturedVideo();
@GET("/videos/new")
Call<Videos> getNewVideo();
@Headers("Content-Type:application/x-www-form-urlencoded")
@FormUrlEncoded
@POST("/auth/create")
Call<SignInResults>insertUser(@Field("username") String username,
@Field("password") String password
);
}
错误(当我尝试在onResponse中获取值时):
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.vid_me_app.FeedFragment$2.onResponse(FeedFragment.java:69)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5751)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
您正在尝试从响应正文中解析SignInResults
个对象。但看看邮递员的反应,这与此毫无关系。
您必须解析与以下对象相对应的对象:
{
"status": true,
"auth": {
"token": "12f6d4123b9947e79f37a4c415bb4b51",
"expires": "2017-04-26 10:38:05",
"user_id": "11272862"
},
"user": {
"user_id": "11272862",
"username": "prozrostyslav",
"full_url": "https://vid.me/prozrostyslav",
"avatar": null,
"avatar_url": "https://d2ha22j8ys3e0o.cloudfront.net/images/default-avatars/13.png?602-2-2-4-9",
"cover": null,
"cover_url": "https://d2ha22j8ys3e0o.cloudfront.net/images/default-covers/03.jpg?602-2-2-4-9",
"displayname": null,
"follower_count": 0,
"likes_count": "0",
"video_count": 0,
"video_views": "0",
"videos_scores": 0,
"comments_scores": 0,
"bio": null
}
}
答案 1 :(得分:0)
您应该检查json的结构,就像在主对象中有2个json对象和状态boolean。这意味着你的主对象包含2个模型(一个是用户,第二个是auth)和布尔值。
package com.ramesh.myapplication.models;
import com.google.gson.annotations.SerializedName;
/**
* Created by Ramesh on 4/26/2016.
*/
public class SignInResult {
@SerializedName("status")
private Boolean status;
@SerializedName("auth")
private Auth auth;
@SerializedName("user")
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Auth getAuth() {
return auth;
}
public void setAuth(Auth auth) {
this.auth = auth;
}
public static class User {
@SerializedName("user_id")
private String userId;
@SerializedName("username")
private String username;
@SerializedName("full_url")
private String fullUrl;
@SerializedName("avatar")
private String avatar;
@SerializedName("avatar_url")
private String avatarUrl;
@SerializedName("cover")
private String cover;
@SerializedName("cover_url")
private String coverUrl;
@SerializedName("displayname")
private String displayname;
@SerializedName("follower_count")
private Integer followerCount;
@SerializedName("likes_count")
private String likesCount;
@SerializedName("video_count")
private Integer videoCount;
@SerializedName("video_views")
private String videoViews;
@SerializedName("videos_scores")
private Integer videosScores;
@SerializedName("comments_scores")
private Integer commentsScores;
@SerializedName("bio")
private String bio;
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullUrl() {
return fullUrl;
}
public void setFullUrl(String fullUrl) {
this.fullUrl = fullUrl;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public String getCover() {
return cover;
}
public void setCover(String cover) {
this.cover = cover;
}
public String getCoverUrl() {
return coverUrl;
}
public void setCoverUrl(String coverUrl) {
this.coverUrl = coverUrl;
}
public String getDisplayname() {
return displayname;
}
public void setDisplayname(String displayname) {
this.displayname = displayname;
}
public Integer getFollowerCount() {
return followerCount;
}
public void setFollowerCount(Integer followerCount) {
this.followerCount = followerCount;
}
public String getLikesCount() {
return likesCount;
}
public void setLikesCount(String likesCount) {
this.likesCount = likesCount;
}
public Integer getVideoCount() {
return videoCount;
}
public void setVideoCount(Integer videoCount) {
this.videoCount = videoCount;
}
public String getVideoViews() {
return videoViews;
}
public void setVideoViews(String videoViews) {
this.videoViews = videoViews;
}
public Integer getVideosScores() {
return videosScores;
}
public void setVideosScores(Integer videosScores) {
this.videosScores = videosScores;
}
public Integer getCommentsScores() {
return commentsScores;
}
public void setCommentsScores(Integer commentsScores) {
this.commentsScores = commentsScores;
}
}
public static class Auth {
@SerializedName("token")
private String token;
@SerializedName("expires")
private String expires;
@SerializedName("user_id")
private String userId;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getExpires() {
return expires;
}
public void setExpires(String expires) {
this.expires = expires;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
}
我创建了一个类和其他子类,您可以根据需要将其更改为独立的类。希望这会有所帮助。