【问题标题】:Correct syntax for adding parameters to get() and post() request using okhttp in Android在 Android 中使用 okhttp 向 get() 和 post() 请求添加参数的正确语法
【发布时间】:2016-03-01 17:24:39
【问题描述】:

我想达到什么目标?

我正在尝试使用 OkHttp 通过 get 和 post 在我的服务器 URL 中发送两个参数,因为我想知道这两种方法的语法。

我尝试了什么?

我已经搜索了有关 OkHttp 的问题,但这些问题并没有解决我的 IllegalArgumentException。

我看过以下链接:

Add query params to a GET request in okhttp in Android

还有这个

How to add parameters to api (http post) using okhttp library in Android

How to add query parameters to a HTTP GET request by OkHttp?

代码 2 的异常:

到目前为止我使用的代码:

1)获取

   urls = chain.request().httpUrl() <-- NullPointerException Line
                    .newBuilder()
                    .scheme("http")
                    .host(SERVER_IP)
                    .addQueryParameter("from", valueFrom)
                    .addQueryParameter("to",valueTo)
                    .build();

        request = chain.request().newBuilder().url(urls).build();

        response = chain.proceed(request);

2)获取

     urls =new HttpUrl.Builder()
                    .host(SERVER_IP)  <--- IllegalArgumentException line
                    .addQueryParameter("from", valueFrom)
                    .addQueryParameter("to", valueTo)
                    .build();

            request = new Request.Builder().url(urls).build(); 

            response = client.newCall(request).execute();  

3)发布

  body = new      
  MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("from",
  valueFrom).addFormDataPart("to",valueTo).build();

        Log.i("Body data",""+body.toString());

        request = new Request.Builder().url(params[0]).post(body).build();

        Log.i("Request data",""+request.toString());

        response = client.newCall(request).execute();

4)发布

  body = new FormEncodingBuilder().add("from", valueFrom).add("to", 
  valueTo).build();

        Log.i("Body data",""+body.toString());

        request = new Request.Builder().url(params[0]).post(body).build();

        Log.i("Request data",""+request.toString());

        response = client.newCall(request).execute();

build.gradle

  dependencies 
  {
   compile files('libs/okhttp-2.5.0.jar')
   compile files('libs/okio-1.6.0.jar')
  }

提前致谢...

编辑:

上面的POST请求代码现在可以正常工作了

但是对于 GET 请求,我仍然没有解决方案。

【问题讨论】:

    标签: android android-studio okhttp


    【解决方案1】:

    只需设置您的 GET 参数即可扩展您的 URL:

    RequestBody body = new FormEncodingBuilder()
                    .add("requestParamName", requestParameter.getRequestParams())
                    .build();
    
    
            Request request = new Request.Builder()
                    .url("https://www.test.com/serviceTest?parama=abc&paramb=123")
                    .post(body)
                    .build();
    

    【讨论】:

    • 你确定这是一个 GET 请求调用吗?
    猜你喜欢
    • 1970-01-01
    • 2015-07-20
    • 2014-08-05
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多