android - 使用 Retrofit2 的 Json 对象请求

标签 android post retrofit2 jsonobjectrequest

我是 retrofit 新手。我完成了所有设置。 我在 build.gradle 文件中添加了这个 gradle

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

我的界面是这样的:

public interface ILoginInterface {
    String BASE_URL= "MY_BASE_URL/";

    @POST("MY/API")
    Call<LoginResponseEntity> startLogin(@Body JSONObject jsonObject);

    class Factory{
        private static ILoginInterface instance;

        public static ILoginInterface getInstance(){
            if(instance==null){
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();

                instance = retrofit.create(ILoginInterface.class);
            }

            return instance;
        }

    }
}

我的调用过程是这样的:

ILoginInterface.Factory.getInstance().startLogin(jsonObject).enqueue(new Callback<LoginResponseEntity>() {
                @Override
                public void onResponse(Call<LoginResponseEntity> call, retrofit2.Response<LoginResponseEntity> response) {
                    Log.d("MS",response.body().fullName);
                }

                @Override
                public void onFailure(Call<LoginResponseEntity> call, Throwable t) {
                    Log.d("MS",t.getMessage());
                }
            });

这里的jsonObject是这样的:

{"user_name":"sajedul Karim", "password":"123456"}

这里似乎一切正常,但我没有得到正确的回应。 我找到了解决办法。它是 here 。有没有人有合适的解决方案,比如 Volley JsonObjectRequest

最佳答案

可能是你在导入

    import org.json.JSONObject;

你应该使用

    import com.google.gson.JsonObject;

然后你会得到它的值(value)。

关于android - 使用 Retrofit2 的 Json 对象请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37638716/

相关文章:

java - 我遇到此错误 java.lang.IndexOutOfBoundsException : Index: 0, 大小:0

Java 安卓开发

java - android java 在第二个 init 的 view.setonclicklistener 处出现空指针异常为什么它们不匹配

php - 来自 Android 的 POST JSON 无法在 PHP 中解码

android - Firebase 多个推送通知不起作用

node.js - Node 错误: SSL23_GET_SERVER_HELLO:unknown protocol and SSL3_GET_RECORD:wrong version number

java - 如何使用 Jsoup 将数据发布到网站

android - 使用retrofit2.0解析JSON对象

android - 格式 @Query 参数 - Retrofit 2

java - 如何使用 Retrofit 来取消转义 HTML 转义符号?