Example usage for com.squareup.okhttp Request body

List of usage examples for com.squareup.okhttp Request body

Introduction

In this page you can find the example usage for com.squareup.okhttp Request body.

Prototype

RequestBody body

To view the source code for com.squareup.okhttp Request body.

Click Source Link

Usage

From source file:com.fysl.app.main.LoginActivity.java

License:Open Source License

private void getFriendsInfoInServer(String allFriends) {

    final ProgressDialog progressDialog = new ProgressDialog(this);

    progressDialog.setMessage("?...");
    progressDialog.setCanceledOnTouchOutside(false);
    progressDialog.show();//  ww  w .  j  a va 2s .co m

    // ???

    RequestBody formBody = new FormEncodingBuilder()

            .add("allFriends", allFriends).build();

    Request request = new Request.Builder().url(Constant.URL_GET_FRIENDS).post(formBody).build();
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Request arg0, IOException arg1) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    progressDialog.dismiss();
                    Toast.makeText(getApplicationContext(), "?...", Toast.LENGTH_SHORT)
                            .show();
                }

            });
        }

        @Override
        public void onResponse(Response arg0) throws IOException {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub

                    progressDialog.dismiss();

                }

            });
            // System.out.println("response--->" + arg0.body().string());

            if (arg0.isSuccessful()) {
                String result = arg0.body().string();

                System.out.println("result--->" + result);
                final JSONObject json = JSONObject.parseObject(Constant.jsonTokener(result));

                if (json.getInteger("code") == 1000) {

                    final JSONArray friends = json.getJSONArray("friends");
                    Map<String, EaseUser> usermap = new HashMap<String, EaseUser>();
                    for (int i = 0; i < friends.size(); i++) {
                        JSONObject friend = friends.getJSONObject(i);
                        EaseUser user = JSON2User.getUser(friend);
                        usermap.put(user.getUsername(), user);

                    }

                    DemoHelper.getInstance().getContactList().putAll(usermap);
                    UserDao dao = new UserDao(LoginActivity.this);
                    dao.saveContactList(new ArrayList(usermap.values()));

                    // // ?
                    // // SDK?
                    //
                    // runOnUiThread(new Runnable() {
                    //
                    // @Override
                    // public void run() {
                    // // TODO Auto-generated method stub
                    // loginHuanxin(friends);
                    // }
                    //
                    // });
                }

            }
        }

    });

}

From source file:com.fysl.app.ui.AddContactActivity.java

License:Open Source License

private void searchUserInServer(String value) {

    final ProgressDialog pd = new ProgressDialog(AddContactActivity.this);
    pd.setCanceledOnTouchOutside(false);
    pd.setMessage("?...");
    pd.show();/*from  w  ww  .jav a 2s .  c  o  m*/

    RequestBody formBody = new FormEncodingBuilder().add("uid", value)

            .build();

    // Constant.KEY_TEL
    Request request = new Request.Builder().url(Constant.URL_SEARCH_USER).post(formBody)

            .build();
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Request arg0, IOException arg1) {

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    pd.dismiss();
                    Toast.makeText(AddContactActivity.this, "??", Toast.LENGTH_SHORT).show();

                }

            });
        }

        @Override
        public void onResponse(Response arg0) throws IOException {

            if (arg0.isSuccessful()) {
                String result = arg0.body().string();
                System.out.println("result--->" + result);
                final JSONObject json = JSONObject.parseObject(Constant.jsonTokener(result));

                if (json.getInteger("code") == 1000) {

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            pd.dismiss();

                        }

                    });

                    JSONObject userInfo = json.getJSONObject("user");

                    startActivity(new Intent(AddContactActivity.this, UserDetailActivity.class)
                            .putExtra("userInfo", userInfo.toJSONString()));

                } else {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            pd.dismiss();
                            Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT)
                                    .show();
                        }

                    });

                }

            } else {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        pd.dismiss();
                    }

                });
                throw new IOException("Unexpected code " + arg0);
            }

        }

    });

}

From source file:com.heroiclabs.sdk.android.util.http.GzipRequestInterceptor.java

License:Apache License

/** {@inheritDoc} */
@Override/*from  w  w  w .ja  va2s  .c om*/
public Response intercept(final Chain chain) throws IOException {
    final Request originalRequest = chain.request();

    // Do not compress requests already encoded, or that are too small.
    if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null
            || originalRequest.body().contentLength() < 300) {
        return chain.proceed(originalRequest);
    }

    final Request compressedRequest = originalRequest.newBuilder().header("Content-Encoding", "gzip")
            .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))).build();
    return chain.proceed(compressedRequest);
}

From source file:com.hexdo.hexexamples.network.GOERetrofit.java

License:Open Source License

public static <S> S createService(Class<S> serviceClass, final String authToken) {
    List<Interceptor> interceptors = httpClient.interceptors();
    interceptors.clear();/*  www .j  av a  2  s.com*/
    if (authToken != null) {
        interceptors.add(new Interceptor() {
            @Override
            public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                Request original = chain.request();

                // Request customization: add request headers
                Request.Builder requestBuilder = original.newBuilder().header("Authorization", authToken)
                        .method(original.method(), original.body());

                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });
    }
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    // set your desired log level
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    interceptors.add(logging);

    Retrofit retrofit = builder.client(httpClient).build();
    return retrofit.create(serviceClass);
}

From source file:com.ibm.watson.developer_cloud.service.RequestBuilderTest.java

License:Open Source License

/**
 * Test with body.//from   w  w w. ja  v  a  2s.  c  o m
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Test
public void testWithBody() throws IOException {
    final File test = new File("src/test/resources/car.png");

    final Request request = RequestBuilder.post(urlWithQuery)
            .withBody(RequestBody.create(HttpMediaType.BINARY_FILE, test)).build();

    final RequestBody requestedBody = request.body();

    assertEquals(test.length(), requestedBody.contentLength());
    assertEquals(HttpMediaType.BINARY_FILE, requestedBody.contentType());
}

From source file:com.ibm.watson.developer_cloud.service.RequestBuilderTest.java

License:Open Source License

/**
 * Test with body JSON object./*  w ww  .  ja  v  a  2  s.  c om*/
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Test
public void testWithBodyJsonJsonObject() throws IOException {
    final JsonObject json = new JsonObject();
    json.addProperty("status", "ok");
    final Request request = RequestBuilder.post(urlWithQuery).withBodyJson(json).build();

    final RequestBody requestedBody = request.body();
    final Buffer buffer = new Buffer();
    requestedBody.writeTo(buffer);

    assertEquals(json.toString(), buffer.readUtf8());
    assertEquals(HttpMediaType.JSON, requestedBody.contentType());
}

From source file:com.ibm.watson.developer_cloud.service.RequestBuilderTest.java

License:Open Source License

/**
 * Test with content string./*from  ww  w  . jav  a 2s  . c o  m*/
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Test
public void testWithContentString() throws IOException {
    final String body = "test2";
    final Request request = RequestBuilder.post(urlWithQuery).withBodyContent(body, HttpMediaType.TEXT_PLAIN)
            .build();

    final RequestBody requestedBody = request.body();
    final Buffer buffer = new Buffer();
    requestedBody.writeTo(buffer);

    assertEquals(body, buffer.readUtf8());
    assertEquals(HttpMediaType.TEXT, requestedBody.contentType());

}

From source file:com.ibm.watson.developer_cloud.service.RequestBuilderTest.java

License:Open Source License

/**
 * Test with form map of string object.//from   w  ww.j a  v  a 2s. co m
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Test
public void testWithFormMapOfStringObject() throws IOException {
    final String body = "p2=p2&foo=bar";

    final Map<String, Object> formParams = new HashMap<String, Object>();
    formParams.put("p2", "p2");
    formParams.put("foo", "bar");

    final Request request = RequestBuilder.post(url).withFormMap(formParams).build();
    final RequestBody requestedBody = request.body();
    final Buffer buffer = new Buffer();
    requestedBody.writeTo(buffer);

    assertEquals(body, buffer.readUtf8());
    assertEquals(MediaType.parse(HttpMediaType.APPLICATION_FORM_URLENCODED), requestedBody.contentType());

}

From source file:com.ibm.watson.developer_cloud.service.RequestBuilderTest.java

License:Open Source License

/**
 * Test with form object array.//from   www. j av a 2s  .c o  m
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Test
public void testWithFormObjectArray() throws IOException {
    final String body = "foo=bar&test1=test2";
    final Request request = RequestBuilder.post(urlWithQuery).withForm("foo", "bar", "test1", "test2").build();

    final RequestBody requestedBody = request.body();

    final Buffer buffer = new Buffer();
    requestedBody.writeTo(buffer);

    assertEquals(body, buffer.readUtf8());
    assertEquals(MediaType.parse(HttpMediaType.APPLICATION_FORM_URLENCODED), requestedBody.contentType());
}

From source file:com.magnet.max.android.rest.qos.internal.CachedRequest.java

License:Apache License

public CachedRequest(Request request) {
    url = request.urlString();// ww  w . ja  v  a 2s  .c  om
    method = request.method();

    parseHeaders(request.headers());

    if (null != request.body()) {
        try {
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);
            body = CacheUtils.copyBody(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}