【问题标题】:Retrofit2: android POST parameters and and GET json arrayRetrofit2:android POST参数和GET json数组
【发布时间】:2016-09-10 13:55:34
【问题描述】:

我正在尝试使用 Retrofit2 解析 JSON 文件 想加个body(参数)

网址如:domain.com/list-all/

{"userId": 7446,"pages":25}

JSON 响应看起来像这种格式

{
  "todaysList": [
    {
      "automatic": false,
      "city": "Trivandrum",
      "countryName": "IND",
      "firstName": "Sarojam",
      "flagExists": true,
      "flagPath": "url",
      "friendReqStatus": 0,
      "fullName": " M",
      "gender": "F",
      "inRequest": false,
      "lastName": "M",
      "optOut": false,
      "outRequest": false,
      "position": 1,
      "profileExist": false,
      "todaysWinner": false,
      "userId": 20726,

    },
    {
      "automatic": false,
      "city": "Trivandrum",
      "countryName": "IND",
      "firstName": "Sarojam",
      "flagExists": true,
      "flagPath": "url",
      "friendReqStatus": 0,
      "fullName": " M",
      "gender": "F",
      "inRequest": false,
      "lastName": "M",
      "optOut": false,
      "outRequest": false,
      "position": 1,
      "profileExist": false,
      "todaysWinner": false,
      "userId": 20726
    },
....
   }

我如何使用 POST 解析它,并使用 Retrofit2 使用两个主体参数

【问题讨论】:

    标签: android json post get retrofit2


    【解决方案1】:

    我是基于Retrofit2解决你的问题,请注意这个!

    首先,在builde.gradle文件中,添加如下依赖:

    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
    

    然后初始化Retrofit:

    Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    

    GsonConverterFactory会自动将JSON字符串转换为Java类对象这一点很重要!

    接下来,创建内容请求数据对象的主体:

    package com.test.xujianzhe.testandroid.retrofit.network_bean;
    
    /**
     * Created by xujianzhe on 16/9/10.
     */
    
    public class TestRequestBean {
    
    /**
     * userId : 7446
     * pages : 25
     */
    
    private int userId;
    private int pages;
    
    public int getUserId() {
        return userId;
    }
    
    public void setUserId(int userId) {
        this.userId = userId;
    }
    
    public int getPages() {
        return pages;
    }
    
    public void setPages(int pages) {
        this.pages = pages;
    }
    }
    

    接下来,创建服务器返回数据结构:

    package com.test.xujianzhe.testandroid.retrofit.network_bean;
    
     import java.util.List;
    
    /**
     * Created by xujianzhe on 16/9/10.
     */
    
     public class TestEntity {
    
    /**
     * automatic : false
     * birthdayPhotoUrl : url
     * city : Trivandrum
     * countryName : IND
     * donated : false
     * expressionId : 8435
     * expressionText : joidj
     * firstName : Sarojam
     * flagExists : true
     * flagPath : url
     * friendReqStatus : 0
     * fullName :  M
     * gender : F
     * inRequest : false
     * lastName : M
     * numberOfTimesDonation : 0
     * optOut : false
     * outRequest : false
     * position : 1
     * profileExist : false
     * todaysWinner : false
     * userId : 20726
     * voted : false
     * votes : 77545
     */
    
    private List<TodaysListBean> todaysList;
    
    public List<TodaysListBean> getTodaysList() {
        return todaysList;
    }
    
    public void setTodaysList(List<TodaysListBean> todaysList) {
        this.todaysList = todaysList;
    }
    
    public static class TodaysListBean {
        private boolean automatic;
        private String birthdayPhotoUrl;
        private String city;
        private String countryName;
        private boolean donated;
        private int expressionId;
        private String expressionText;
        private String firstName;
        private boolean flagExists;
        private String flagPath;
        private int friendReqStatus;
        private String fullName;
        private String gender;
        private boolean inRequest;
        private String lastName;
        private int numberOfTimesDonation;
        private boolean optOut;
        private boolean outRequest;
        private int position;
        private boolean profileExist;
        private boolean todaysWinner;
        private int userId;
        private boolean voted;
        private int votes;
    
        public boolean isAutomatic() {
            return automatic;
        }
    
        public void setAutomatic(boolean automatic) {
            this.automatic = automatic;
        }
    
        public String getBirthdayPhotoUrl() {
            return birthdayPhotoUrl;
        }
    
        public void setBirthdayPhotoUrl(String birthdayPhotoUrl) {
            this.birthdayPhotoUrl = birthdayPhotoUrl;
        }
    
        public String getCity() {
            return city;
        }
    
        public void setCity(String city) {
            this.city = city;
        }
    
        public String getCountryName() {
            return countryName;
        }
    
        public void setCountryName(String countryName) {
            this.countryName = countryName;
        }
    
        public boolean isDonated() {
            return donated;
        }
    
        public void setDonated(boolean donated) {
            this.donated = donated;
        }
    
        public int getExpressionId() {
            return expressionId;
        }
    
        public void setExpressionId(int expressionId) {
            this.expressionId = expressionId;
        }
    
        public String getExpressionText() {
            return expressionText;
        }
    
        public void setExpressionText(String expressionText) {
            this.expressionText = expressionText;
        }
    
        public String getFirstName() {
            return firstName;
        }
    
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
    
        public boolean isFlagExists() {
            return flagExists;
        }
    
        public void setFlagExists(boolean flagExists) {
            this.flagExists = flagExists;
        }
    
        public String getFlagPath() {
            return flagPath;
        }
    
        public void setFlagPath(String flagPath) {
            this.flagPath = flagPath;
        }
    
        public int getFriendReqStatus() {
            return friendReqStatus;
        }
    
        public void setFriendReqStatus(int friendReqStatus) {
            this.friendReqStatus = friendReqStatus;
        }
    
        public String getFullName() {
            return fullName;
        }
    
        public void setFullName(String fullName) {
            this.fullName = fullName;
        }
    
        public String getGender() {
            return gender;
        }
    
        public void setGender(String gender) {
            this.gender = gender;
        }
    
        public boolean isInRequest() {
            return inRequest;
        }
    
        public void setInRequest(boolean inRequest) {
            this.inRequest = inRequest;
        }
    
        public String getLastName() {
            return lastName;
        }
    
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
    
        public int getNumberOfTimesDonation() {
            return numberOfTimesDonation;
        }
    
        public void setNumberOfTimesDonation(int numberOfTimesDonation) {
            this.numberOfTimesDonation = numberOfTimesDonation;
        }
    
        public boolean isOptOut() {
            return optOut;
        }
    
        public void setOptOut(boolean optOut) {
            this.optOut = optOut;
        }
    
        public boolean isOutRequest() {
            return outRequest;
        }
    
        public void setOutRequest(boolean outRequest) {
            this.outRequest = outRequest;
        }
    
        public int getPosition() {
            return position;
        }
    
        public void setPosition(int position) {
            this.position = position;
        }
    
        public boolean isProfileExist() {
            return profileExist;
        }
    
        public void setProfileExist(boolean profileExist) {
            this.profileExist = profileExist;
        }
    
        public boolean isTodaysWinner() {
            return todaysWinner;
        }
    
        public void setTodaysWinner(boolean todaysWinner) {
            this.todaysWinner = todaysWinner;
        }
    
        public int getUserId() {
            return userId;
        }
    
        public void setUserId(int userId) {
            this.userId = userId;
        }
    
        public boolean isVoted() {
            return voted;
        }
    
        public void setVoted(boolean voted) {
            this.voted = voted;
        }
    
        public int getVotes() {
            return votes;
        }
    
        public void setVotes(int votes) {
            this.votes = votes;
        }
    }
    }
    

    创建界面:

    package com.test.xujianzhe.testandroid.retrofit;
    
    import com.test.xujianzhe.testandroid.retrofit.network_bean.TestEntity;
    import com.test.xujianzhe.testandroid.retrofit.network_bean.TestRequestBean;
    
    import retrofit2.Call;
    import retrofit2.http.Body;
    import retrofit2.http.POST;
    
    /**
     * Created by xujianzhe on 16/9/10.
     */
    
    public interface ITestRetrofit {
    
         @POST
         Call<TestEntity> testOperation(@Body TestRequestBean requestBean);
    }
    

    最后,创建请求:

    TestRequestBean testRequestBean = new TestRequestBean();
        testRequestBean.setPages(2);
        testRequestBean.setUserId(2);
         retrofit.create(ITestRetrofit.class).testOperation(testRequestBean).enqueue(new Callback<TestEntity>() {
            @Override
            public void onResponse(Call<TestEntity> call,    Response<TestEntity> response) {
                // response
            }
    
            @Override
            public void onFailure(Call<TestEntity> call, Throwable t) {
    
            }
        });
    

    完整的工作代码如下:

    package com.test.xujianzhe.testandroid.retrofit.network_bean;
    
    import android.content.Context;
    
    import com.test.xujianzhe.testandroid.retrofit.ITestRetrofit;
    
    import retrofit2.Call;
    import retrofit2.Callback;
    import retrofit2.Response;
    import retrofit2.Retrofit;
    import retrofit2.converter.gson.GsonConverterFactory;
    
    /**
     * Created by xujianzhe on 16/9/10.
     */
    
    public class RetrofitWork {
    
    public static void requestOperation(Context context) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        TestRequestBean testRequestBean = new TestRequestBean();
        testRequestBean.setPages(2);
        testRequestBean.setUserId(2);
        retrofit.create(ITestRetrofit.class).testOperation(testRequestBean).enqueue(new Callback<TestEntity>() {
            @Override
            public void onResponse(Call<TestEntity> call, Response<TestEntity> response) {
                // response
            }
    
            @Override
            public void onFailure(Call<TestEntity> call, Throwable t) {
    
            }
        });
    }
    
    }
    

    希望以上内容能解决你的问题!

    【讨论】:

    • 感谢您的支持。请您提供“ITestRetrofit.class”接口和/或TodaysListBean.class的代码。接口类将是最有用的......因为知道如何发布它非常重要
    • 哦,对不起,我忘记提交了,真的很抱歉!我重新编辑了答案,请查看!
    • 上面已经提供了TodaysListBean,可以滚动查看代码块!
    【解决方案2】:

    创建一个包含“userId”和“pages”等 2 个字段的类。

    我建议您阅读this,如果您的问题仍然存在,请在 cmets 中询问。

    【讨论】:

    • 我已经按照本教程..和其他..我的问题(初学者)我需要在接口中使用@POST 方法并传递两个值..并解析 josn 响应..问题仍然存在跨度>
    • 你能解释一下解决办法吗
    • 我如何用类文件调用.enqeue 并得到响应,这是真正的问题
    猜你喜欢
    • 2017-02-10
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 2012-02-10
    • 2018-06-19
    • 2013-05-13
    相关资源
    最近更新 更多