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:BenchMarkTest.java

License:Open Source License

void doOkHttpRequest() {
    ++okhttp_task_cnt;/*from   w w  w.j a v  a  2 s  .c  o  m*/
    try {
        OkHttpClient client = new OkHttpClient();

        Main.HelloRequest req = new Main.HelloRequest();
        req.user = "okhttp";
        req.text = Integer.toString((int) okhttp_task_cnt);
        //Benchmark 64KB/128KB
        /*req.dumpContent = new byte[64*1024];
        Random rand = new Random();
        rand.nextBytes(req.dumpContent);*/

        final byte[] flatArray = new byte[req.getSerializedSize()];
        final CodedOutputByteBufferNano output = CodedOutputByteBufferNano.newInstance(flatArray);
        req.writeTo(output);
        RequestBody reqBody = RequestBody.create(MediaType.parse("application/octet-stream"), flatArray);

        //normal request
        Request request = new Request.Builder().url("http://118.89.24.72:8080/mars/hello2")
                .addHeader("Cache-Control", "no-cache").addHeader("Content-Type", "application/octet-stream")
                .addHeader("Connection", "close").addHeader("Accept", "*/*").post(reqBody).build();

        okhttp_task_time = System.currentTimeMillis();
        // Execute the request and retrieve the response.
        Response response = client.newCall(request).execute();

        ResponseBody body = response.body();
        Main.HelloResponse helloResp = Main.HelloResponse.parseFrom(body.bytes());
        body.close();

        long curr = System.currentTimeMillis();
        okhttp_suc_time += curr - okhttp_task_time;
        ++okhttp_task_suc;
        //Log.i(TAG, "http type:" + type + ", suc cost:" + (curr - okhttp_task_time) + ", count:" + okhttp_task_cnt + ", suc count:" + okhttp_task_suc + ", ctn:" + helloResp.errmsg);
    } catch (Exception e) {
        Log.e(TAG, "http fail cost:" + (System.currentTimeMillis() - okhttp_task_time) + ", count:"
                + okhttp_task_cnt);
    }
}

From source file:FunctionalTest.java

License:Apache License

public static void presignedGetObject_test1() throws Exception {
    println("Test: presignedGetObject(String bucketName, String objectName)");
    String fileName = createFile(3 * MB);
    client.putObject(bucketName, fileName, fileName);

    String urlString = client.presignedGetObject(bucketName, fileName);
    Request.Builder requestBuilder = new Request.Builder();
    Request request = requestBuilder.url(HttpUrl.parse(urlString)).method("GET", null).build();
    OkHttpClient transport = new OkHttpClient();
    Response response = transport.newCall(request).execute();

    if (response != null) {
        if (response.isSuccessful()) {
            OutputStream os = Files.newOutputStream(Paths.get(fileName + ".downloaded"),
                    StandardOpenOption.CREATE);
            ByteStreams.copy(response.body().byteStream(), os);
            response.body().close();//w ww  . j  a v  a 2 s  .  co m
            os.close();
        } else {
            String errorXml = "";

            // read entire body stream to string.
            Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
            if (scanner.hasNext()) {
                errorXml = scanner.next();
            }

            println("FAILED", response, errorXml);
        }
    } else {
        println("NO RESPONSE");
    }

    if (!Arrays.equals(Files.readAllBytes(Paths.get(fileName)),
            Files.readAllBytes(Paths.get(fileName + ".downloaded")))) {
        println("CONTENT DIFFERS");
    }

    Files.delete(Paths.get(fileName));
    Files.delete(Paths.get(fileName + ".downloaded"));
    client.removeObject(bucketName, fileName);
}

From source file:FunctionalTest.java

License:Apache License

public static void presignedGetObject_test2() throws Exception {
    println("Test: presignedGetObject(String bucketName, String objectName, Integer expires)");
    String fileName = createFile(3 * MB);
    client.putObject(bucketName, fileName, fileName);

    String urlString = client.presignedGetObject(bucketName, fileName, 3600);
    Request.Builder requestBuilder = new Request.Builder();
    Request request = requestBuilder.url(HttpUrl.parse(urlString)).method("GET", null).build();
    OkHttpClient transport = new OkHttpClient();
    Response response = transport.newCall(request).execute();

    if (response != null) {
        if (response.isSuccessful()) {
            OutputStream os = Files.newOutputStream(Paths.get(fileName + ".downloaded"),
                    StandardOpenOption.CREATE);
            ByteStreams.copy(response.body().byteStream(), os);
            response.body().close();/*from   w  w w  . j a v  a 2  s  .  co m*/
            os.close();
        } else {
            String errorXml = "";

            // read entire body stream to string.
            Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
            if (scanner.hasNext()) {
                errorXml = scanner.next();
            }

            println("FAILED", response, errorXml);
        }
    } else {
        println("NO RESPONSE");
    }

    if (!Arrays.equals(Files.readAllBytes(Paths.get(fileName)),
            Files.readAllBytes(Paths.get(fileName + ".downloaded")))) {
        println("CONTENT DIFFERS");
    }

    Files.delete(Paths.get(fileName));
    Files.delete(Paths.get(fileName + ".downloaded"));
    client.removeObject(bucketName, fileName);
}

From source file:FunctionalTest.java

License:Apache License

public static void presignedPutObject_test1() throws Exception {
    println("Test: presignedPutObject(String bucketName, String objectName)");
    String fileName = createFile(3 * MB);
    String urlString = client.presignedPutObject(bucketName, fileName);

    Request.Builder requestBuilder = new Request.Builder();
    Request request = requestBuilder.url(HttpUrl.parse(urlString))
            .method("PUT", RequestBody.create(null, Files.readAllBytes(Paths.get(fileName)))).build();
    OkHttpClient transport = new OkHttpClient();
    Response response = transport.newCall(request).execute();

    if (response != null) {
        if (!response.isSuccessful()) {
            String errorXml = "";

            // read entire body stream to string.
            Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
            if (scanner.hasNext()) {
                errorXml = scanner.next();
            }//w w  w.  java2 s. c  o  m

            println("FAILED", response, errorXml);
        }
    } else {
        println("NO RESPONSE");
    }

    Files.delete(Paths.get(fileName));
    client.removeObject(bucketName, fileName);
}

From source file:FunctionalTest.java

License:Apache License

public static void presignedPutObject_test2() throws Exception {
    println("Test: presignedPutObject(String bucketName, String objectName, Integer expires)");
    String fileName = createFile(3 * MB);
    String urlString = client.presignedPutObject(bucketName, fileName, 3600);

    Request.Builder requestBuilder = new Request.Builder();
    Request request = requestBuilder.url(HttpUrl.parse(urlString))
            .method("PUT", RequestBody.create(null, Files.readAllBytes(Paths.get(fileName)))).build();
    OkHttpClient transport = new OkHttpClient();
    Response response = transport.newCall(request).execute();

    if (response != null) {
        if (!response.isSuccessful()) {
            String errorXml = "";

            // read entire body stream to string.
            Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
            if (scanner.hasNext()) {
                errorXml = scanner.next();
            }/*from ww w. ja  v  a 2 s  . co m*/

            println("FAILED", response, errorXml);
        }
    } else {
        println("NO RESPONSE");
    }

    Files.delete(Paths.get(fileName));
    client.removeObject(bucketName, fileName);
}

From source file:FunctionalTest.java

License:Apache License

public static void presignedPostPolicy_test() throws Exception {
    println("Test: presignedPostPolicy(PostPolicy policy)");
    String fileName = createFile(3 * MB);
    PostPolicy policy = new PostPolicy(bucketName, fileName, DateTime.now().plusDays(7));
    policy.setContentRange(1 * MB, 4 * MB);
    Map<String, String> formData = client.presignedPostPolicy(policy);

    MultipartBuilder multipartBuilder = new MultipartBuilder();
    multipartBuilder.type(MultipartBuilder.FORM);
    for (Map.Entry<String, String> entry : formData.entrySet()) {
        multipartBuilder.addFormDataPart(entry.getKey(), entry.getValue());
    }/* ww  w.j  ava  2  s.c o  m*/
    multipartBuilder.addFormDataPart("file", fileName, RequestBody.create(null, new File(fileName)));

    Request.Builder requestBuilder = new Request.Builder();
    Request request = requestBuilder.url(endpoint + "/" + bucketName).post(multipartBuilder.build()).build();
    OkHttpClient transport = new OkHttpClient();
    Response response = transport.newCall(request).execute();

    if (response != null) {
        if (!response.isSuccessful()) {
            String errorXml = "";

            // read entire body stream to string.
            Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
            if (scanner.hasNext()) {
                errorXml = scanner.next();
            }

            println("FAILED", response, errorXml);
        }
    } else {
        println("NO RESPONSE");
    }

    Files.delete(Paths.get(fileName));
    client.removeObject(bucketName, fileName);
}

From source file:abtlibrary.utils.as24ApiClient.ApiClient.java

License:Apache License

public ApiClient() {
    httpClient = new OkHttpClient();

    verifyingSsl = true;//from  www . ja  v  a2s.  co m

    json = new JSON(this);

    /*
     * Use RFC3339 format for date and datetime.
     * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
     */
    this.dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    // Always use UTC as the default time zone when dealing with date (without time).
    this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    initDatetimeFormat();

    // Be lenient on datetime formats when parsing datetime from string.
    // See <code>parseDatetime</code>.
    this.lenientDatetimeFormat = true;

    // Set default User-Agent.
    setUserAgent("Swagger-Codegen/1.0.0/java");

    // Setup authentications (key: authentication name, value: authentication).
    authentications = new HashMap<String, Authentication>();
    authentications.put("oauth2", new OAuth());
    // Prevent the authentications from being modified.
    authentications = Collections.unmodifiableMap(authentications);
}

From source file:alberto.avengers.model.rest.RestDataSource.java

License:Mozilla Public License

@Inject
public RestDataSource() {
    OkHttpClient client = new OkHttpClient();

    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);

    MarvelSigningIterceptor signingIterceptor = new MarvelSigningIterceptor(BuildConfig.MARVEL_PUBLIC_KEY,
            BuildConfig.MARVEL_PRIVATE_KEY);

    client.interceptors().add(signingIterceptor);
    client.interceptors().add(loggingInterceptor);

    Gson customGsonInstance = new GsonBuilder().registerTypeAdapter(new TypeToken<List<Character>>() {
    }.getType(), new MarvelResultsDeserializer<Character>())

            .registerTypeAdapter(new TypeToken<List<CollectionItem>>() {
            }.getType(), new MarvelResultsDeserializer<CollectionItem>())

            .create();/*  w w w. j  a v  a  2  s .c o m*/

    Retrofit marvelApiAdapter = new Retrofit.Builder().baseUrl(MarvelApi.END_POINT)
            .addConverterFactory(GsonConverterFactory.create(customGsonInstance))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).client(client).build();

    mMarvelApi = marvelApiAdapter.create(MarvelApi.class);
}

From source file:api.QueryManager.java

License:Open Source License

private QueryManager() {
    client = new OkHttpClient();

    longRateLimiter = RateLimiter.create(DEFAULT_LONG_RATE_LIMIT);
    shortRateLimiter = RateLimiter.create(DEFAULT_SHORT_RATE_LIMIT);

    // Default endpoint to NA
    endpoint = endpoints.get(Region.NA);

    // Default region to NA
    region = Region.NA;//from w w w  .ja v a 2s . com
}

From source file:apijson.demo.client.manager.HttpManager.java

License:Apache License

/**
 * @param url// ww  w  .  j  a  v  a  2s . com
 * @return
 */
private OkHttpClient getHttpClient(String url) {
    Log.i(TAG, "getHttpClient  url = " + url);
    if (StringUtil.isNotEmpty(url, true) == false) {
        Log.e(TAG, "getHttpClient  StringUtil.isNotEmpty(url, true) == false >> return null;");
        return null;
    }

    OkHttpClient client = new OkHttpClient();
    client.setCookieHandler(new HttpHead());
    client.setConnectTimeout(15, TimeUnit.SECONDS);
    client.setWriteTimeout(10, TimeUnit.SECONDS);
    client.setReadTimeout(10, TimeUnit.SECONDS);

    return client;
}