List of usage examples for com.squareup.okhttp HttpUrl parse
public static HttpUrl parse(String url)
From source file:io.github.hidroh.materialistic.accounts.UserServicesClient.java
License:Apache License
@Override public void submit(Context context, final String title, final String content, final boolean isUrl, final Callback callback) { Pair<String, String> credentials = AppUtils.getCredentials(context); if (credentials == null) { callback.onDone(false);/*w ww . j a v a 2 s .c om*/ return; } /** * The flow: * POST /submit with acc, pw * if 302 to /login, considered failed * POST /r with fnid, fnop, title, url or text * if 302 to /newest, considered successful * if 302 to /x, considered error, maybe duplicate or invalid input * if 200 or anything else, considered error */ // fetch submit page with given credentials mClient.newCall(new Request.Builder() .url(HttpUrl.parse(BASE_WEB_URL).newBuilder().addPathSegment(SUBMIT_PATH).build()) .post(new FormEncodingBuilder().add(LOGIN_PARAM_ACCT, credentials.first) .add(LOGIN_PARAM_PW, credentials.second).build()) .build()).enqueue(new com.squareup.okhttp.Callback() { @Override public void onFailure(Request request, IOException e) { postError(callback); } @Override public void onResponse(Response response) throws IOException { final boolean redirect = response.code() == HttpURLConnection.HTTP_MOVED_TEMP; if (redirect) { // redirect = failed login postResult(callback, false); } else { // grab fnid from HTML and submit doSubmit(title, content, getInputValue(response.body().string(), SUBMIT_PARAM_FNID), isUrl, callback); } } }); }
From source file:io.github.hidroh.materialistic.accounts.UserServicesClient.java
License:Apache License
@WorkerThread private void doSubmit(String title, String content, String fnid, boolean isUrl, final Callback callback) { if (TextUtils.isEmpty(fnid)) { postError(callback);/* w w w.j ava 2s . c o m*/ return; } mClient.newCall(new Request.Builder() .url(HttpUrl.parse(BASE_WEB_URL).newBuilder().addPathSegment(SUBMIT_POST_PATH).build()) .post(new FormEncodingBuilder().add(SUBMIT_PARAM_FNID, fnid).add(SUBMIT_PARAM_FNOP, DEFAULT_FNOP) .add(SUBMIT_PARAM_TITLE, title).add(isUrl ? SUBMIT_PARAM_URL : SUBMIT_PARAM_TEXT, content) .build()) .build()).enqueue(new com.squareup.okhttp.Callback() { @Override public void onFailure(Request request, IOException e) { postError(callback); } @Override public void onResponse(Response response) throws IOException { boolean redirect = response.code() == HttpURLConnection.HTTP_MOVED_TEMP; if (!redirect) { postError(callback); return; } String location = response.header(HEADER_LOCATION); switch (location) { case DEFAULT_SUBMIT_REDIRECT: postResult(callback, true); break; default: postError(callback); break; } } }); }
From source file:io.instacount.client.decoders.InstacountJacksonDecoder.java
License:Apache License
/** * Helper to construct an optionally present instance of {@link CounterLocationInfo} from the Feign {@link Response} * .// w w w . j av a2 s.co m * * @param response * @return */ private Optional<CounterLocationInfo> constructCounterLocationInfo(final Response response) { final Optional<CounterLocationInfo> optCounterInfo; final Collection<String> locationHeaders = response.headers().get("Location"); if (!locationHeaders.isEmpty()) { final String location = locationHeaders.iterator().next(); final HttpUrl httpUrl = HttpUrl.parse(location); Preconditions.checkNotNull(httpUrl); final String counterName = httpUrl.pathSegments().get(1); final CounterLocationInfo counterLocationHeaderInfo = new CounterLocationInfo(location, counterName); optCounterInfo = Optional.fromNullable(counterLocationHeaderInfo); } else { optCounterInfo = Optional.absent(); } return optCounterInfo; }
From source file:io.kodokojo.commons.utils.docker.DockerSupport.java
License:Open Source License
public boolean waitUntilHttpRequestRespond(String url, long time, TimeUnit unit, ServiceIsUp serviceIsUp) { if (isBlank(url)) { throw new IllegalArgumentException("url must be defined."); }//w w w . j a v a2 s .c o m long now = System.currentTimeMillis(); long delta = unit != null ? TimeUnit.MILLISECONDS.convert(time, unit) : time; long endTime = now + delta; long until = 0; OkHttpClient httpClient = new OkHttpClient(); HttpUrl httpUrl = HttpUrl.parse(url); int nbTry = 0; boolean available = false; do { nbTry++; available = tryRequest(httpUrl, httpClient, serviceIsUp); if (!available) { try { Thread.sleep(20); } catch (InterruptedException e) { Thread.interrupted(); break; } now = System.currentTimeMillis(); until = endTime - now; } } while (until > 0 && !available); if (LOGGER.isDebugEnabled()) { LOGGER.debug(url + " " + (available ? "Success" : "Failed after " + nbTry + " try")); } return available; }
From source file:io.minio.MinioClient.java
License:Apache License
/** * Creates Minio client object using given endpoint, port, access key, secret key and secure option. * * </p><b>Example:</b><br> * <pre>{@code MinioClient minioClient = * new MinioClient("play.minio.io", 9000, "YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", false); * }</pre>//from w ww . j av a 2 s . c o m * * @param endpoint Request endpoint. Endpoint is an URL, domain name, IPv4 or IPv6 address.<pre> * Valid endpoints: * * https://s3.amazonaws.com * * https://s3.amazonaws.com/ * * https://play.minio.io:9000 * * http://play.minio.io:9010/ * * localhost * * localhost.localdomain * * play.minio.io * * 127.0.0.1 * * 192.168.1.60 * * ::1</pre> * * @param port Valid port. It should be in between 1 and 65535. Unused if endpoint is an URL. * @param accessKey Access key to access service in endpoint. * @param secretKey Secret key to access service in endpoint. * @param secure If true, access endpoint using HTTPS else access it using HTTP. * * @see #MinioClient(String endpoint) * @see #MinioClient(URL url) * @see #MinioClient(String endpoint, String accessKey, String secretKey) * @see #MinioClient(URL url, String accessKey, String secretKey) * @see #MinioClient(String endpoint, int port, String accessKey, String secretKey) * @see #MinioClient(String endpoint, String accessKey, String secretKey, boolean secure) */ public MinioClient(String endpoint, int port, String accessKey, String secretKey, boolean secure) throws InvalidEndpointException, InvalidPortException { if (endpoint == null) { throw new InvalidEndpointException(NULL_STRING, "null endpoint"); } if (port < 0 || port > 65535) { throw new InvalidPortException(port, "port must be in range of 1 to 65535"); } HttpUrl url = HttpUrl.parse(endpoint); if (url != null) { if (!"/".equals(url.encodedPath())) { throw new InvalidEndpointException(endpoint, "no path allowed in endpoint"); } // treat Amazon S3 host as special case String amzHost = url.host(); if (amzHost.endsWith(AMAZONAWS_COM) && !amzHost.equals(S3_AMAZONAWS_COM)) { throw new InvalidEndpointException(endpoint, "for Amazon S3, host should be 's3.amazonaws.com' in endpoint"); } HttpUrl.Builder urlBuilder = url.newBuilder(); Scheme scheme = Scheme.HTTP; if (secure) { scheme = Scheme.HTTPS; } urlBuilder.scheme(scheme.toString()); if (port > 0) { urlBuilder.port(port); } this.baseUrl = urlBuilder.build(); this.accessKey = accessKey; this.secretKey = secretKey; return; } // endpoint may be a valid hostname, IPv4 or IPv6 address if (!this.isValidEndpoint(endpoint)) { throw new InvalidEndpointException(endpoint, "invalid host"); } // treat Amazon S3 host as special case if (endpoint.endsWith(AMAZONAWS_COM) && !endpoint.equals(S3_AMAZONAWS_COM)) { throw new InvalidEndpointException(endpoint, "for amazon S3, host should be 's3.amazonaws.com'"); } Scheme scheme = Scheme.HTTP; if (secure) { scheme = Scheme.HTTPS; } if (port == 0) { this.baseUrl = new HttpUrl.Builder().scheme(scheme.toString()).host(endpoint).build(); } else { this.baseUrl = new HttpUrl.Builder().scheme(scheme.toString()).host(endpoint).port(port).build(); } this.accessKey = accessKey; this.secretKey = secretKey; }
From source file:it.analysis.ReportDumpTest.java
License:Open Source License
private void verifyUrl(String url) throws IOException { HttpUrl httpUrl = HttpUrl.parse(url); Request request = new Request.Builder().url(httpUrl).get().build(); Response response = new OkHttpClient().newCall(request).execute(); assertThat(response.isSuccessful()).as(httpUrl.toString()).isTrue(); assertThat(response.body().string()).as(httpUrl.toString()).isNotEmpty(); }
From source file:jonas.tool.saveForOffline.FaviconFetcher.java
License:Open Source License
public List<String> getPotentialFaviconUrls(Document document) { List<String> iconUrls = new ArrayList<String>(); HttpUrl base = HttpUrl.parse(document.baseUri()); for (String cssQuery : htmlIconCssQueries) { for (Element e : document.select(cssQuery)) { if (e.hasAttr("href")) { iconUrls.add(e.attr("href")); }/*from w w w . j a va 2s. c om*/ if (e.hasAttr("content")) { iconUrls.add(e.attr("content")); } if (e.hasAttr("src")) { iconUrls.add(e.attr("src")); } } } for (String path : hardcodedIconPaths) { HttpUrl url = HttpUrl.parse("http://" + HttpUrl.parse(document.baseUri()).host() + path); iconUrls.add(url.toString()); } for (ListIterator<String> i = iconUrls.listIterator(); i.hasNext();) { HttpUrl httpUrl = base.resolve(i.next()); if (httpUrl != null) { i.set(httpUrl.toString()); } else { i.remove(); } } return iconUrls; }
From source file:keywhiz.cli.CommandExecutor.java
License:Apache License
public void executeCommand() throws IOException { if (command == null) { if (config.version) { System.out.println("Version: " + APP_VERSION); } else {//ww w.j a va 2 s . c o m System.err.println("Must specify a command."); parentCommander.usage(); } return; } HttpUrl url; if (Strings.isNullOrEmpty(config.url)) { url = HttpUrl.parse("https://localhost:4444"); System.out.println("Server URL not specified (--url flag), assuming " + url); } else { url = HttpUrl.parse(config.url); if (url == null) { System.err.print("Invalid URL " + config.url); return; } } KeywhizClient client; OkHttpClient httpClient; String user = config.getUser().orElse(USER_NAME.value()); Path cookiePath = cookieDir.resolve(format(".keywhiz.%s.cookie", user)); try { List<HttpCookie> cookieList = ClientUtils.loadCookies(cookiePath); httpClient = ClientUtils.sslOkHttpClient(config.getDevTrustStore(), cookieList); client = new KeywhizClient(mapper, httpClient, url); // Try a simple get request to determine whether or not the cookies are still valid if (!client.isLoggedIn()) { throw new UnauthorizedException(); } } catch (IOException e) { // Either could not find the cookie file, or the cookies were expired -- must login manually. httpClient = ClientUtils.sslOkHttpClient(config.getDevTrustStore(), ImmutableList.of()); client = new KeywhizClient(mapper, httpClient, url); char[] password = ClientUtils.readPassword(user); client.login(user, password); Arrays.fill(password, '\0'); } // Save/update the cookies if we logged in successfully ClientUtils.saveCookies((CookieManager) httpClient.getCookieHandler(), cookiePath); Printing printing = new Printing(client); Command cmd = Command.valueOf(command.toUpperCase().trim()); switch (cmd) { case LIST: new ListAction((ListActionConfig) commands.get(command), client, printing).run(); break; case DESCRIBE: new DescribeAction((DescribeActionConfig) commands.get(command), client, printing).run(); break; case ADD: new AddAction((AddActionConfig) commands.get(command), client, mapper).run(); break; case DELETE: new DeleteAction((DeleteActionConfig) commands.get(command), client).run(); break; case ASSIGN: new AssignAction((AssignActionConfig) commands.get(command), client).run(); break; case UNASSIGN: new UnassignAction((UnassignActionConfig) commands.get(command), client).run(); break; case LOGIN: // User is already logged in at this point break; default: commander.usage(); } }
From source file:name.gudong.translate.reject.modules.ApiServiceModel.java
License:Open Source License
@Provides @Singleton//w w w . j av a 2 s . c o m ApiService provideApiService() { Retrofit retrofit = new Retrofit.Builder().baseUrl(new BaseUrl() { @Override public HttpUrl url() { return HttpUrl.parse(SpUtils.getUrlByLocalSetting()); } }) // for RxJava .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()).build(); return retrofit.create(ApiService.class); }
From source file:net.callmeike.android.simplesync.sync.SimpleSync.java
License:Apache License
public int sync(String url, ContentProviderClient provider) throws IOException, RemoteException { RestService restService = DaggerNetComponent.builder().netModule(new NetModule(HttpUrl.parse(url))).build() .restService();/*from ww w.jav a 2 s .c om*/ List<ContentValues> data = restService.loadData().execute().body(); if (null == data) { return 0; } int len = data.size(); if (len <= 0) { return 0; } ContentValues[] recs = new ContentValues[len]; data.toArray(recs); return provider.bulkInsert(CONTENT_URI, recs); }