Example usage for com.squareup.okhttp Response body

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

Introduction

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

Prototype

ResponseBody body

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

Click Source Link

Usage

From source file:com.digitalglobe.iipfoundations.productservice.gbdx.GBDxWorkflow.java

public static String status(String wf_id, String authorization) throws Exception {
    logger.trace("Entering Status - workflow id: {}", wf_id);
    String status = "";

    Properties gbdx = GBDxCredentialManager.getGBDxCredentials();

    Request workflow_status_request = new Request.Builder()
            .url("https://geobigdata.io/workflows/v1/workflows/" + wf_id).get()
            .addHeader("content-type", "application/json").addHeader("authorization", authorization).build();
    OkHttpClient client = new OkHttpClient();
    String body = null;//from w w  w.  j  a v  a 2s .  c o m
    try {
        Response response = client.newCall(workflow_status_request).execute();
        body = response.body().string();

        JSONObject json = new JSONObject(body);
        JSONObject state = json.getJSONObject("state");
        status = state.getString("state");

    } catch (JSONException e) {
        logger.warn("Unable to parse response for workflow id: {}, Error: {}, Body: {}", wf_id, e.getMessage(),
                body);
    } catch (IOException e) {
        logger.warn(e.getMessage());
    }

    logger.trace("Leaving Status - status: {}", status);
    return status;
}

From source file:com.digitalglobe.iipfoundations.productservice.orderservice.OrderService.java

/**
 * /*from  www.  java2s  .c o m*/
 * @param cat_id
 * @param auth_token
 * @return - the order_id
 * @throws IOException
 * @throws OrderServiceException 
 */
public static String order1b(String cat_id, String auth_token) throws IOException, OrderServiceException {
    String request = generateOrder1bRequestBody(cat_id);
    System.out.println(request);
    MediaType mediaType = MediaType.parse("application/json");
    RequestBody request_body = RequestBody.create(mediaType, request);

    //Properties gbdx = GBDxCredentialManager.getGBDxCredentials();

    Request search_request = new Request.Builder().url("http://orders.iipfoundations.com/order/v1")
            .post(request_body).addHeader("content-type", "application/json")
            .addHeader("authorization", "Basic " + auth_token).addHeader("username", username)
            .addHeader("password", password).build();

    OkHttpClient client = new OkHttpClient();
    System.out.println(search_request.toString());
    Response response = client.newCall(search_request).execute();
    if (200 == response.code()) {
        String body = response.body().string();
        System.out.println(body);

        JSONObject obj = new JSONObject(body);
        JSONArray orders = obj.getJSONArray("orders");
        JSONObject order = orders.getJSONObject(0);
        int id = order.getInt("id");
        return Integer.toString(id);
    } else {
        System.out.println(response.body().string());
        logger.error(response.message());
        throw new OrderServiceException(response.message());
    }

}

From source file:com.dreamdigitizers.androidsoundcloudapi.core.Api.java

private Api(final String pClientId, final String pOauthToken) {
    OkHttpClient okHttpClient = new OkHttpClient();

    okHttpClient.interceptors().add(new Interceptor() {
        @Override//from   ww  w  .j  av a2  s .c  o  m
        public Response intercept(Chain pChain) throws IOException {
            Request request = pChain.request();
            HttpUrl.Builder builder = request.httpUrl().newBuilder();
            builder.addQueryParameter("client_id", pClientId);
            if (!TextUtils.isEmpty(pOauthToken)) {
                builder.addQueryParameter("oauth_token", pOauthToken);
            }
            HttpUrl httpUrl = builder.build();
            Log.d(Api.TAG, httpUrl.url().toString());
            request = request.newBuilder().url(httpUrl).build();
            Response response = pChain.proceed(request);
            String bodyString = response.body().string();
            response = response.newBuilder()
                    .body(ResponseBody.create(response.body().contentType(), bodyString)).build();
            Log.d(Api.TAG, bodyString);
            return response;
        }
    });

    Retrofit retrofit = new Retrofit.Builder().baseUrl(IApi.API_URL__BASE).client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();

    this.mApi = retrofit.create(IApi.class);
}

From source file:com.dreamfactory.kurtishu.pretty.view.task.DownloadImagTask.java

License:Apache License

private void downloadImg(String url) {
    Request request = new Request.Builder().url(url).build();
    OkHttpClient okHttpClient = new OkHttpClient();
    try {/*  www .  j  a v  a 2s  .c o m*/
        Response response = okHttpClient.newCall(request).execute();
        if (null != response && response.isSuccessful()) {
            String filePath = storeImgToSDCard(response.body().byteStream());
            setPostMessage(EXECUTE_STATE_DOWNLOAD_SUCCESS, filePath);
        } else {
            setPostMessage(ExecutableThread.EXECUTE_STATE_FAILURE, "Internet error!");
        }
    } catch (IOException e) {
        Logger.e("Error message: " + e.toString());
        setPostMessage(ExecutableThread.EXECUTE_STATE_FAILURE, e.getMessage());
    }
}

From source file:com.drjing.xibao.common.http.AsyncHttpResponseHandler.java

License:Apache License

protected void sendSuccessMessage(Response response) {
    try {/*from   w  ww. j a  va  2 s  .  c o m*/
        sendMessage(obtainMessage(SUCCESS_MESSAGE,
                new Object[] { new Integer(response.code()), response.headers(), response.body().string() }));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.enstage.wibmo.util.HttpUtil.java

License:Apache License

public static String postDataUseOkHttp(String posturl, byte postData[], boolean useCache, MediaType mediaType)
        throws Exception {
    URL url;//from   w  w  w.j a  v a  2s .  co  m
    long stime = System.currentTimeMillis();
    try {
        url = new URL(posturl);

        RequestBody body = RequestBody.create(mediaType, postData);

        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if (useCache == false) {
            builder.addHeader("Cache-Control", "no-cache");
        }
        builder.post(body);
        Request request = builder.build();

        if (okhttpinit == false) {
            Log.w(TAG, "WibmoSDK init was false; " + client.getSslSocketFactory());

            if (client.getSslSocketFactory() == null) {
                setSSLstuff();
            }
        }

        Response res = client.newCall(request).execute();

        // Read the response.
        if (res.code() != HttpURLConnection.HTTP_OK) {
            Log.e(TAG, "Bad res code: " + res.code());
            Log.e(TAG, "Url was: " + posturl.toString());
            Log.e(TAG, "HTTP response: " + res.message() + "; " + res.body().string());
            return null;
        }

        return res.body().string();
    } finally {
        long etime = System.currentTimeMillis();
        Log.i(TAG, "time dif: " + (etime - stime));
    }
}

From source file:com.evandroid.musica.utils.Net.java

License:Open Source License

public static String getUrlAsString(URL paramURL) throws IOException {
    Request request = new Request.Builder().header("User-Agent", USER_AGENT).url(paramURL).build();
    OkHttpClient client = new OkHttpClient();
    Response response = client.newCall(request).execute();

    return response.body().string();
}

From source file:com.example.diego.proyecto1edd.TestWebServer.java

public String getString(String metodo, RequestBody formBody) {

    try {/*from  w w w  .j  av a  2s. c o m*/
        URL url = new URL("http://192.168.0.100:5000/" + metodo);
        Request request = new Request.Builder().url(url).post(formBody).build();
        Response response = webClient.newCall(request).execute();//Aqui obtiene la respuesta en dado caso si hayas pues un return en python
        String response_string = response.body().string();//y este seria el string de las respuesta
        return response_string;
    } catch (MalformedURLException ex) {
        java.util.logging.Logger.getLogger(com.example.diego.proyecto1edd.TestWebServer.class.getName())
                .log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        java.util.logging.Logger.getLogger(com.example.diego.proyecto1edd.TestWebServer.class.getName())
                .log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.example.ivy.picassodemo.MyOkHttpDownloader.java

License:Apache License

@Override
public Response load(Uri uri, int networkPolicy) throws IOException {
    CacheControl cacheControl = null;/* ww w .  j a v a  2 s. c om*/
    if (networkPolicy != 0) {
        if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
            cacheControl = CacheControl.FORCE_CACHE;
        } else {
            CacheControl.Builder builder = new CacheControl.Builder();
            if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) {
                builder.noCache();
            }
            if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) {
                builder.noStore();
            }
            cacheControl = builder.build();
        }
    }

    Request.Builder builder = new Request.Builder().url(uri.toString());
    if (cacheControl != null) {
        builder.cacheControl(cacheControl);
    }

    com.squareup.okhttp.Response response = client.newCall(builder.build()).execute();
    int responseCode = response.code();
    if (responseCode >= 300) {
        response.body().close();
        throw new ResponseException(responseCode + " " + response.message(), networkPolicy, responseCode);
    }

    boolean fromCache = response.cacheResponse() != null;

    ResponseBody responseBody = response.body();
    return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength());
}

From source file:com.example.jony.myapp.reader_APP.ui.DailyDetailsActivity.java

License:Open Source License

@Override
protected void onDataRefresh() {
    Request.Builder builder = new Request.Builder();
    builder.url(url);//w  w w .  ja v  a  2s  .  c o m
    Request request = builder.build();
    HttpUtil.enqueue(request, new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            handler.sendEmptyMessage(CONSTANT.ID_FAILURE);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            String res = response.body().string();
            DebugUtils.DLog(res);
            Gson gson = new Gson();
            dailyDetailsBean = gson.fromJson(res, DailyDetailsBean.class);

            cache.execSQL(DailyTable.updateBodyContent(DailyTable.NAME, dailyDetailsBean.getTitle(),
                    dailyDetailsBean.getBody()));
            cache.execSQL(DailyTable.updateBodyContent(DailyTable.COLLECTION_NAME, dailyDetailsBean.getTitle(),
                    dailyDetailsBean.getBody()));
            cache.execSQL(DailyTable.updateLargePic(DailyTable.NAME, dailyDetailsBean.getTitle(),
                    dailyDetailsBean.getImage()));
            cache.execSQL(DailyTable.updateLargePic(DailyTable.COLLECTION_NAME, dailyDetailsBean.getTitle(),
                    dailyDetailsBean.getImage()));

            imageUrl = dailyDetailsBean.getImage();
            body = dailyDetailsBean.getBody();

            handler.sendEmptyMessage(CONSTANT.ID_SUCCESS);
        }
    });
}