Example usage for com.squareup.okhttp OkHttpClient OkHttpClient

List of usage examples for com.squareup.okhttp OkHttpClient OkHttpClient

Introduction

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

Prototype

public OkHttpClient() 

Source Link

Usage

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

public static Properties getS3Credentials(String auth_header) {
    Properties creds = new Properties();
    OkHttpClient client = new OkHttpClient();
    client.setHostnameVerifier(new HostnameVerifier() {
        @Override//from   w ww.  j a v a  2  s .  c om
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });
    Request request = new Request.Builder().url("https://geobigdata.io/s3creds/v1/prefix").get()
            .addHeader("content-type", "application/json").addHeader("authorization", auth_header).build();

    try {
        Response response = client.newCall(request).execute();
        String body = response.body().string();

        creds = parseResponse(body);

    } catch (IOException io) {
        System.out.println("ERROR!");
        System.out.println(io.getMessage());
    }

    return creds;
}

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;// w ww .java2  s.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 w  ww  . j a  v a  2 s . com*/
 * @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   w  w  w .  j  a v 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 {//from  w  ww  .  j av  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.droiddevil.myuber.data.DataModule.java

License:Apache License

static OkHttpClient createOkHttpClient(Context context) {
    OkHttpClient client = new OkHttpClient();
    File cacheDir = new File(context.getCacheDir(), "http_cache");
    try {/*from   ww  w  .j ava  2  s . c om*/
        Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
        client.setCache(cache);
    } catch (IOException e) {
        Timber.e(e, "Could not create http cache");
    }
    return client;
}

From source file:com.dzhyun.sdk.DzhChannel.java

License:Open Source License

@ReactMethod
public void connect(final String url, final int id) {
    OkHttpClient client = new OkHttpClient();

    client.setConnectTimeout(10, TimeUnit.SECONDS);
    client.setWriteTimeout(10, TimeUnit.SECONDS);
    // Disable timeouts for read
    client.setReadTimeout(0, TimeUnit.MINUTES);

    Request request = new Request.Builder().tag(id).url(url).build();

    WebSocketCall.create(client, request).enqueue(new WebSocketListener() {

        @Override/*w  w  w . jav a 2s  . co  m*/
        public void onOpen(WebSocket webSocket, Response response) {
            mWebSocketConnections.put(id, webSocket);
            WritableMap params = Arguments.createMap();
            params.putInt("id", id);
            sendEvent("dzhChannelOpen", params);
        }

        @Override
        public void onClose(int code, String reason) {
            WritableMap params = Arguments.createMap();
            params.putInt("id", id);
            params.putInt("code", code);
            params.putString("reason", reason);
            sendEvent("dzhChannelClosed", params);
        }

        @Override
        public void onFailure(IOException e, Response response) {
            notifyWebSocketFailed(id, e.getMessage());
        }

        @Override
        public void onPong(Buffer buffer) {
        }

        @Override
        public void onMessage(BufferedSource bufferedSource, WebSocket.PayloadType payloadType) {
            String message;
            if (payloadType == WebSocket.PayloadType.BINARY) {

                try {
                    message = Pb2Json.toJson(bufferedSource.readByteArray());
                    bufferedSource.close();
                } catch (IOException e) {
                    FLog.e(ReactConstants.TAG, "decode pb failed " + id, e);
                    return;
                }

            } else {
                try {
                    message = bufferedSource.readUtf8();
                } catch (IOException e) {
                    notifyWebSocketFailed(id, e.getMessage());
                    return;
                }
                try {
                    bufferedSource.close();
                } catch (IOException e) {
                    FLog.e(ReactConstants.TAG, "Could not close BufferedSource for WebSocket id " + id, e);
                }

            }

            WritableMap params = Arguments.createMap();
            params.putInt("id", id);
            params.putString("data", message);
            sendEvent("dzhChannelMessage", params);
        }
    });

    // Trigger shutdown of the dispatcher's executor so this process can exit cleanly
    client.getDispatcher().getExecutorService().shutdown();
}

From source file:com.ephemeraldreams.gallyshuttle.data.DataModule.java

License:Apache License

/**
 * Provide a HTTP client.//from   w  w  w . ja  va  2 s . c o  m
 *
 * @param application Application to get cache directory from.
 * @return Cached HTTP client.
 */
@Provides
@ApplicationScope
OkHttpClient provideOkHttpClient(Application application) {
    OkHttpClient client = new OkHttpClient();
    File cacheDir = new File(application.getCacheDir(), "http");
    Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
    client.setCache(cache);
    return client;
}

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.app.di.modules.ApiModule.java

License:Apache License

@Provides
@Singleton/*from  w w w  . j a va 2 s .  co m*/
@Named("noCache")
OkHttpClient provideNoCacheOkHttpClient(HttpLoggingInterceptor loggingInterceptor,
        @Named("userAgent") String userAgentValue) {
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(loggingInterceptor);
    client.networkInterceptors().add(new UserAgentInterceptor(userAgentValue));
    client.networkInterceptors().add(new StethoInterceptor());
    return client;
}