Example usage for com.squareup.okhttp OkHttpClient newCall

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

Introduction

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

Prototype

public Call newCall(Request request) 

Source Link

Document

Prepares the request to be executed at some point in the future.

Usage

From source file:BenchMarkTest.java

License:Open Source License

void doOkHttpRequest() {
    ++okhttp_task_cnt;/*from   w w  w.ja v  a  2s  .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();//from  w  w  w. j  a  v a2 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();//w w  w  .  ja  va2 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();
            }/*from   w  w  w. j  a va 2  s .com*/

            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  . j  ava  2 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 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());
    }/*  w w  w  .  ja v a 2s.co  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:apijson.demo.client.manager.HttpManager.java

License:Apache License

/**
 * @param client//  w  w  w  .ja va  2s  .  c o  m
 * @param request
 * @return
 * @throws Exception
 */
private String getResponseJson(OkHttpClient client, Request request) throws Exception {
    if (client == null || request == null) {
        Log.e(TAG, "getResponseJson  client == null || request == null >> return null;");
        return null;
    }
    Response response = client.newCall(request).execute();
    return response.isSuccessful() ? response.body().string() : null;
}

From source file:appewtc.masterung.testdrivinglicense.ConfirmScoreActivity.java

public void clickOKConfirm(View view) {

    String urlPHP = "http://swiftcodingthai.com/toey/add_score.php";

    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = new FormEncodingBuilder().add("isAdd", "true").add("id_login", loginStrings[0])
            .add("Date", dateString).add("Score", scoreString).build();
    Request.Builder builder = new Request.Builder();
    Request request = builder.url(urlPHP).post(requestBody).build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override//from w  w  w  .j  a v  a  2 s  . c  om
        public void onFailure(Request request, IOException e) {

        }

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

            Intent intent = new Intent(ConfirmScoreActivity.this, ScoreListView.class);
            intent.putExtra("login", loginStrings);
            startActivity(intent);
            finish();

        }
    });

}

From source file:appewtc.masterung.testdrivinglicense.ScoreListView.java

private void createListView() {

    String urlPHP = "http://swiftcodingthai.com/toey/get_score_where.php";

    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = new FormEncodingBuilder().add("isAdd", "true").add("id_login", loginStrings[0])
            .build();/*from   w  ww.  java 2  s  .c o m*/
    Request.Builder builder = new Request.Builder();
    Request request = builder.url(urlPHP).post(requestBody).build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

        }

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

            String strResponse = response.body().string();
            Log.d("10AugV2", "strResponse ==> " + strResponse);

            try {

                JSONArray jsonArray = new JSONArray(strResponse);

                String[] dateStrings = new String[jsonArray.length()];
                String[] scoreStrings = new String[jsonArray.length()];

                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    dateStrings[i] = jsonObject.getString("Date");
                    scoreStrings[i] = "? = " + jsonObject.getString("Score")
                            + " ?";

                } // for

                CoaurseAdapter coaurseAdapter = new CoaurseAdapter(ScoreListView.this, 1, dateStrings,
                        scoreStrings);
                listView.setAdapter(coaurseAdapter);

            } catch (Exception e) {
                e.printStackTrace();
            }

        } // onResponse
    });

}

From source file:appewtc.masterung.testdrivinglicense.SignUpActivity.java

private void upLoadNewUser() {

    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = new FormEncodingBuilder().add("isAdd", "true").add("Name", nameString)
            .add("Surname", surnameString).add("Age", ageString).add("User", userString)
            .add("Password", passwordString).build();
    Request.Builder builder = new Request.Builder();
    Request request = builder.url(urlPHP).post(requestBody).build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override/*from ww  w .j  a  v  a2s .  c  o m*/
        public void onFailure(Request request, IOException e) {

        }

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

            finish();

        }
    });

}