使用Android

时间:2015-11-27 13:33:42

标签: android android-studio okhttp

我想要达到什么目标?

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

我曾尝试过什么?

我已经在搜索SO以查找有关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中的异常:

enter image description here

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

1)GET

   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)GET

     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)POST

  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)POST

  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请求我仍然没有解决方案。

1 个答案:

答案 0 :(得分:-2)

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

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();