Example usage for com.squareup.okhttp Request.Builder url

List of usage examples for com.squareup.okhttp Request.Builder url

Introduction

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

Prototype

HttpUrl url

To view the source code for com.squareup.okhttp Request.Builder url.

Click Source Link

Usage

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 w w  .jav  a 2s .  c o  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 . jav  a2s.c  om
            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  .  ja  v a2 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();
            }/*w w w  .ja  va2s . c  om*/

            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());
    }//from   www  . j  ava 2s  .  com
    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: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 ww  .  ja  v a  2  s .  co m
        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 w  w  . ja v  a2 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// w ww. j a v  a  2  s .  com
        public void onFailure(Request request, IOException e) {

        }

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

            finish();

        }
    });

}

From source file:butter.droid.base.providers.media.AnimeProvider.java

License:Open Source License

@Override
public Call getList(final ArrayList<Media> existingList, Filters filters, final Callback callback) {
    final ArrayList<Media> currentList;
    if (existingList == null) {
        currentList = new ArrayList<>();
    } else {/*  w  w w  .j  ava 2 s.co  m*/
        currentList = (ArrayList<Media>) existingList.clone();
    }

    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("limit", "30"));

    if (filters == null) {
        filters = new Filters();
    }

    if (filters.keywords != null) {
        params.add(new NameValuePair("keywords", filters.keywords));
    }

    if (filters.genre != null) {
        params.add(new NameValuePair("genre", filters.genre));
    }

    if (filters.order == Filters.Order.ASC) {
        params.add(new NameValuePair("order", "1"));
    } else {
        params.add(new NameValuePair("order", "-1"));
    }

    String sort;
    switch (filters.sort) {
    default:
    case POPULARITY:
        sort = "popularity";
        break;
    case YEAR:
        sort = "year";
        break;
    //            case DATE:
    //                sort = "updated";
    //                break;
    case RATING:
        sort = "rating";
        break;
    case ALPHABET:
        sort = "name";
        break;
    }

    params.add(new NameValuePair("sort", sort));

    String url = API_URLS[CURRENT_API] + "animes/";
    if (filters.page != null) {
        url += filters.page;
    } else {
        url += "1";
    }

    Request.Builder requestBuilder = new Request.Builder();
    String query = buildQuery(params);
    url = url + "?" + query;
    requestBuilder.url(url);
    requestBuilder.tag(MEDIA_CALL);

    Timber.d("AnimeProvider", "Making request to: " + url);

    return fetchList(currentList, requestBuilder, filters, callback);
}

From source file:butter.droid.base.providers.media.AnimeProvider.java

License:Open Source License

/**
 * Fetch the list of movies from Haruhichan
 *
 * @param currentList    Current shown list to be extended
 * @param requestBuilder Request to be executed
 * @param callback       Network callback
 * @return Call/* w  w w .  ja v a  2s  . c  o  m*/
 */
private Call fetchList(final ArrayList<Media> currentList, final Request.Builder requestBuilder,
        final Filters filters, final Callback callback) {
    return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            String url = requestBuilder.build().urlString();
            if (CURRENT_API >= API_URLS.length - 1) {
                callback.onFailure(e);
            } else {
                if (url.contains(API_URLS[CURRENT_API])) {
                    url = url.replace(API_URLS[CURRENT_API], API_URLS[CURRENT_API + 1]);
                    CURRENT_API++;
                } else {
                    url = url.replace(API_URLS[CURRENT_API - 1], API_URLS[CURRENT_API]);
                }
                requestBuilder.url(url);
                fetchList(currentList, requestBuilder, filters, callback);
            }
        }

        @Override
        public void onResponse(Response response) throws IOException {
            try {
                if (response.isSuccessful()) {
                    String responseStr = response.body().string();

                    ArrayList<LinkedTreeMap<String, Object>> list = null;
                    if (responseStr.isEmpty()) {
                        list = new ArrayList<>();
                    } else {
                        list = (ArrayList<LinkedTreeMap<String, Object>>) mGson.fromJson(responseStr,
                                ArrayList.class);
                    }

                    AnimeResponse result = new AnimeResponse(list);
                    if (list == null) {
                        callback.onFailure(new NetworkErrorException("Empty response"));
                    } else {
                        ArrayList<Media> formattedData = result.formatListForPopcorn(currentList);
                        callback.onSuccess(filters, formattedData, list.size() > 0);
                        return;
                    }
                }
            } catch (Exception e) {
                callback.onFailure(e);
            }
            callback.onFailure(new NetworkErrorException("Couldn't connect to AnimeAPI"));
        }
    });
}