Example usage for com.squareup.okhttp HttpUrl parse

List of usage examples for com.squareup.okhttp HttpUrl parse

Introduction

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

Prototype

public static HttpUrl parse(String url) 

Source Link

Document

Returns a new HttpUrl representing url if it is a well-formed HTTP or HTTPS URL, or null if it isn't.

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 .ja v a 2  s.  com
            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  ww . j  av  a2  s . 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 .j  av a2s  . 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();
            }//ww w .  j  a  va 2 s .  co  m

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

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

From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java

License:Apache License

@Ignore
@Test/*from www  .  j a  va 2 s  . co  m*/
public void networkInterceptorsCannotChangeServerAddress() throws Exception {
    server.enqueue(new MockResponse().setResponseCode(500));

    Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Address address = chain.connection().getRoute().getAddress();
            String sameHost = address.getUriHost();
            int differentPort = address.getUriPort() + 1;
            return chain.proceed(chain.request().newBuilder()
                    .url(HttpUrl.parse("http://" + sameHost + ":" + differentPort + "/")).build());
        }
    };
    client.networkInterceptors().add(interceptor);

    Request request = new Request.Builder().url(server.url("/")).build();

    try {
        client.newCall(request).execute();
        fail();
    } catch (IllegalStateException expected) {
        assertEquals("network interceptor " + interceptor + " must retain the same host and port",
                expected.getMessage());
    }
}

From source file:com.ae.apps.pnrstatus.service.NetworkService.java

License:Open Source License

public String doGetRequest(final String httpUrl, List<Pair<String, String>> params) throws Exception {
    HttpUrl.Builder urlBuilder = HttpUrl.parse(httpUrl).newBuilder();

    // Add Query Params if present
    if (null != params && !params.isEmpty()) {
        for (Pair<String, String> param : params) {
            urlBuilder.addQueryParameter(param.first, param.second);
        }/*from w ww.  ja va2 s.com*/
    }

    String url = urlBuilder.build().toString();

    try {
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();

        return response.body().string();
    } catch (IOException ex) {
        throw new StatusException(ex.getMessage(), StatusException.ErrorCodes.URL_ERROR);
    }
}

From source file:com.andrew67.ddrfinder.adapters.MapLoaderV1.java

License:Open Source License

@Override
protected ApiResult doInBackground(LatLngBounds... boxes) {
    // Fetch machine data in JSON format
    JSONArray jArray = new JSONArray();
    try {//from  www . j av  a  2  s.com
        if (boxes.length == 0)
            throw new IllegalArgumentException("No boxes passed to doInBackground");
        final LatLngBounds box = boxes[0];

        final OkHttpClient client = new OkHttpClient();
        final String LOADER_API_URL = sharedPref.getString(SettingsActivity.KEY_PREF_API_URL, "");
        final HttpUrl requestURL = HttpUrl.parse(LOADER_API_URL).newBuilder()
                .addQueryParameter("source", "android")
                .addQueryParameter("latupper", "" + box.northeast.latitude)
                .addQueryParameter("longupper", "" + box.northeast.longitude)
                .addQueryParameter("latlower", "" + box.southwest.latitude)
                .addQueryParameter("longlower", "" + box.southwest.longitude).build();

        Log.d("api", "Request URL: " + requestURL);
        final Request get = new Request.Builder().header("User-Agent", BuildConfig.APPLICATION_ID + " "
                + BuildConfig.VERSION_NAME + "/Android?SDK=" + Build.VERSION.SDK_INT).url(requestURL).build();

        final Response response = client.newCall(get).execute();
        final int statusCode = response.code();
        Log.d("api", "Status code: " + statusCode);

        // Data loaded OK
        if (statusCode == 200) {
            final String jResponse = response.body().string();
            Log.d("api", "Raw API result: " + jResponse);
            jArray = new JSONArray(jResponse);
        }
        // Code used for invalid parameters; in this case exceeding
        // the limits of the boundary box
        else if (statusCode == 400) {
            return new ApiResultV1(ApiResultV1.ERROR_ZOOM);
        }
        // Unexpected error code
        else {
            return new ApiResultV1(ApiResultV1.ERROR_API);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Return list
    ArrayList<ArcadeLocation> out = new ArrayList<>();
    try {
        for (int i = 0; i < jArray.length(); ++i) {
            final JSONObject obj = (JSONObject) jArray.get(i);
            final String name = obj.getString("name");

            boolean closed = false;
            if (ArcadeLocation.CLOSED.matcher(name).matches()) {
                closed = true;
            }
            // Fields added after ddr-finder 1.0 API should be
            // explicitly tested for, in order to maintain
            // compatibility with deployments of older versions
            boolean hasDDR = false;
            if (obj.has("hasDDR") && obj.getInt("hasDDR") == 1) {
                hasDDR = true;
            }

            out.add(new ArcadeLocationV1(obj.getInt("id"), name, obj.getString("city"),
                    new LatLng(obj.getDouble("latitude"), obj.getDouble("longitude")), hasDDR, closed));
        }
    } catch (Exception e) {
        out.clear();
    }
    return new ApiResultV1(out, boxes[0]);
}

From source file:com.andrew67.ddrfinder.adapters.MapLoaderV3.java

License:Open Source License

@Override
protected ApiResult doInBackground(LatLngBounds... boxes) {
    ApiResult result = null;/*from  w w  w  .  j  ava 2 s.  co m*/
    try {
        if (boxes.length == 0)
            throw new IllegalArgumentException("No boxes passed to doInBackground");
        final LatLngBounds box = boxes[0];

        String datasrc = sharedPref.getString(SettingsActivity.KEY_PREF_API_SRC, "");
        if (SettingsActivity.API_SRC_CUSTOM.equals(datasrc)) {
            datasrc = sharedPref.getString(SettingsActivity.KEY_PREF_API_SRC_CUSTOM, "");
        }

        final OkHttpClient client = new OkHttpClient();
        final String LOADER_API_URL = sharedPref.getString(SettingsActivity.KEY_PREF_API_URL, "");
        final HttpUrl requestURL = HttpUrl.parse(LOADER_API_URL).newBuilder()
                .addQueryParameter("version", "" + SettingsActivity.API_V30)
                .addQueryParameter("datasrc", datasrc)
                .addQueryParameter("latupper", "" + box.northeast.latitude)
                .addQueryParameter("lngupper", "" + box.northeast.longitude)
                .addQueryParameter("latlower", "" + box.southwest.latitude)
                .addQueryParameter("lnglower", "" + box.southwest.longitude).build();

        Log.d("api", "Request URL: " + requestURL);
        final Request get = new Request.Builder().header("User-Agent", BuildConfig.APPLICATION_ID + " "
                + BuildConfig.VERSION_NAME + "/Android?SDK=" + Build.VERSION.SDK_INT).url(requestURL).build();

        final Response response = client.newCall(get).execute();
        final int statusCode = response.code();
        Log.d("api", "Status code: " + statusCode);

        // Data/error loaded OK
        if (statusCode == 200 || statusCode == 400) {
            final Gson gson = new Gson();
            result = gson.fromJson(response.body().charStream(), Result.class);
            result.setBounds(box);
            Log.d("api", "Raw API result: " + gson.toJson(result, Result.class));
        }
        // Unexpected error code
        else {
            throw new RuntimeException("Unexpected HTTP status code: " + statusCode);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.auth0.android.Auth0.java

License:Open Source License

private HttpUrl resolveConfiguration(@Nullable String configurationDomain, @NonNull HttpUrl domainUrl) {
    HttpUrl url = ensureValidUrl(configurationDomain);
    if (url == null) {
        final String host = domainUrl.host();
        if (host.endsWith(DOT_AUTH0_DOT_COM)) {
            String[] parts = host.split("\\.");
            if (parts.length > 3) {
                url = HttpUrl.parse("https://cdn." + parts[parts.length - 3] + DOT_AUTH0_DOT_COM);
            } else {
                url = HttpUrl.parse(AUTH0_US_CDN_URL);
            }//  ww w.  ja va2 s.c  om
        } else {
            url = domainUrl;
        }
    }
    return url;
}

From source file:com.auth0.android.Auth0.java

License:Open Source License

private HttpUrl ensureValidUrl(String url) {
    if (url == null) {
        return null;
    }//from  w w w. j  a  v  a  2s .co  m
    String safeUrl = url.startsWith("http") ? url : "https://" + url;
    return HttpUrl.parse(safeUrl);
}