【问题标题】:How to send Body Data to GET Method Request android如何将正文数据发送到 GET 方法请求 android
【发布时间】:2018-10-18 04:44:57
【问题描述】:

这样,我想向 GET API 发送 json body 请求

试过了,没用

 public static void getQuestionsListApi2(final String requestId, final String timestamp,
                                        final ImageProcessingCallback.downloadQuestionsCallbacks callback,
                                        final Context context) {

    try {
       String url = NetUrls.downloadQuestions;

        final JSONObject jsonBody = new JSONObject();
        jsonBody.put("requestId", requestId);
        jsonBody.put("timestamp", timestamp);
        final String mRequestBody = jsonBody.toString();
        Log.i("params", String.valueOf(jsonBody));
        Log.i("URL", url);
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, **jsonBody**, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.v("TAG", "Success " + jsonObject);
                callback.downloadQuestionsCallbacksSuccess(jsonObject.toString());
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.v("TAG", "ERROR " + volleyError.toString());
            }


        });

        request.setRetryPolicy(new DefaultRetryPolicy(
                DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 0,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        RequestQueue queue = Volley.newRequestQueue(context);
        queue.add(request);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}


        request.setRetryPolicy(new DefaultRetryPolicy(
                DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 0,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


        RequestQueue queue = Volley.newRequestQueue(context);
        queue.add(request);

这是我在使用 GET 方法发送 JSONRequest 时使用的代码,我从服务器 和服务器收到 400 错误响应,除了 url 表单中的数据。我发送 jsonBody 对象作为参数。任何解决方案。

【问题讨论】:

  • 很容易使用改造API调用。
  • @android-team,改造中的任何示例我们如何发送 json 正文以获取 android 中的方法?
  • 你的服务器上线了吗?你能在这里提供问题的网址吗?
  • 是的,出于安全原因,我的服务器现已上线,屏幕截图中的网址已更改
  • 我面临同样的问题。任何机构都使用 Retorfit 解决了这个问题?

标签: android api android-volley


【解决方案1】:

如果你想在GET请求体中传递Json数据,你必须使用Query注解

Call<YourNodelClass> getSomeDetails(@Query("threaded") String threaded, @Query("limit") int limit);

这将作为 Json 对象 {"threaded": "val", "limit": 3} 传递。

我试过了,这个只是工作代码。

【讨论】:

  • 好吧,我认为这不是正确的解决方案,因为服务器将在query 中而不是在body 中获取数据。
  • 你想我都试过了。请检查它肯定会工作。
【解决方案2】:

试试这个代码..

将以下依赖项添加到应用级 gradle 文件中。

    implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

然后在下面所有单独的类

第一个改造对象创建类如下..

public class ApiClient {
private final static String BASE_URL = "https://dog.ceo/api/breed/";

public static ApiClient apiClient;
private Retrofit retrofit = null;
private Retrofit retrofit2 = null;

public static ApiClient getInstance() {
    if (apiClient == null) {
        apiClient = new ApiClient();
    }
    return apiClient;
}

//private static Retrofit storeRetrofit = null;

public Retrofit getClient() {
    return getClient(null);
}


private Retrofit getClient(final Context context) {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.readTimeout(60, TimeUnit.SECONDS);
    client.writeTimeout(60, TimeUnit.SECONDS);
    client.connectTimeout(60, TimeUnit.SECONDS);
    client.addInterceptor(interceptor);
    client.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            return chain.proceed(request);
        }
    });

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


    return retrofit;
}

}

然后制作如下api接口..

public interface ApiInterface {
@POST("login/")
Call<LoginResponseModel> loginCheck(@Body UserData data);
}

让 pojo 调用服务器响应和用户输入 ..

public class LoginResponseModel {
@SerializedName("message") // here define your json key
private String msg;

public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}

}

用户输入类

public class UserData {
private String email,password;

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

}

    private void getLogin(){
    ApiInterface apiInterface=ApiClient.getInstance().getClient().create(ApiInterface.class);
    UserData data=new UserData();
    data.setEmail("abc@gmail.com");
    data.setPassword("123456");
    Call<LoginResponseModel> loginResponseModelCall=apiInterface.loginCheck(data);
    loginResponseModelCall.enqueue(new Callback<LoginResponseModel>() {
        @Override
        public void onResponse(Call<LoginResponseModel> call, retrofit2.Response<LoginResponseModel> response) {
            if (response.isSuccessful() &&  response !=null && response.body() !=null){
                LoginResponseModel loginResponseModel=response.body();
            }
        }

        @Override
        public void onFailure(Call<LoginResponseModel> call, Throwable t) {

        }
    });
}

当不需要用户交互时使用GET方法。

您创建 pojo 类,然后使用下面的链接生成 pojo 类,将您的 json 数据粘贴到.. http://www.jsonschema2pojo.org/

【讨论】:

  • java.lang.IllegalArgumentException: 非正文 HTTP 方法不能包含 @Body 为 public interface ApiInterface { @GET("questions/") Call&lt;JSONObject&gt; loginCheck(@Body JSONObject data); } 获取此错误
  • 我遇到了同样的问题: 我想将正文数据(JSON 对象)传递给 GET() 我需要做什么?
【解决方案3】:

您可以使用改造来发送带有正文的请求。 http://square.github.io/retrofit/

易于使用的库,例如:

@GET("[url node]")
Single<Response<ResponseBody>> doSmt(@Header("Authorization") String token, @Body ListRequest name);

另外,看看这里关于 get 方法的 body HTTP GET with request body

更新

带有请求正文的GET方法是可选的here。但是,this RFC7231 document 说,

在 GET 请求上发送有效负载正文可能会导致一些现有的 拒绝请求的实现。

这意味着不建议这样做。使用 POST 方法使用请求正文。

从维基百科查看此表。

【讨论】:

  • 我现在正在使用 Volley 库,所以 volley 中有任何方法可以实现这一点。
  • 这不是解决方案。 GET 注释不能与改造中的 Body 注释一起使用。
猜你喜欢
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 2021-02-17
  • 2019-05-23
  • 2022-01-25
  • 2020-04-25
  • 2017-06-23
  • 2021-08-13
相关资源
最近更新 更多