List of usage examples for com.squareup.okhttp HttpUrl get
public static HttpUrl get(URI uri)
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void buildRequestUsingHttpUrl() throws Exception { server.enqueue(new MockResponse()); HttpUrl httpUrl = HttpUrl.get(server.getUrl("/")); Request request = new Request.Builder().url(httpUrl).build(); assertEquals(httpUrl, request.httpUrl()); FiberOkHttpTestUtil.executeInFiberRecorded(client, request).assertSuccessful(); }
From source file:com.google.caliper.runner.resultprocessor.OkHttpUploadHandler.java
License:Apache License
@Override public boolean upload(URI uri, String content, String mediaType, Optional<UUID> apiKey, Trial trial) { HttpUrl url = HttpUrl.get(uri); if (apiKey.isPresent()) { url = url.newBuilder().addQueryParameter("key", apiKey.get().toString()).build(); }/* ww w . jav a 2 s . c o m*/ RequestBody body = RequestBody.create(MediaType.parse(mediaType), content); Request request = new Request.Builder().url(url).post(body).build(); try { Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return true; } else { ResultsUploader.logger.fine("Failed upload response: " + response.code()); } } catch (IOException e) { ResultsUploader.logUploadFailure(trial, e); } return false; }
From source file:com.granita.contacticloudsync.resource.DavResourceFinder.java
License:Open Source License
public void findResources(Service service) throws URISyntaxException { URI baseURI = serverInfo.getBaseURI(); String domain = null;/*from ww w .j a v a2 s . c o m*/ HttpUrl principalUrl = null; Set<HttpUrl> homeSets = new HashSet<>(); if (service == Service.CALDAV) { calendars.clear(); taskLists.clear(); } else if (service == Service.CARDDAV) addressbooks.clear(); log.info("*** STARTING COLLECTION DISCOVERY FOR SERVICE " + service.name.toUpperCase(Locale.US) + "***"); if ("http".equals(baseURI.getScheme()) || "https".equals(baseURI.getScheme())) { HttpUrl userURL = HttpUrl.get(baseURI); /* check whether: 1. user-given URL is a calendar 2. user-given URL has a calendar-home-set property (i.e. is a principal URL) */ log.info( "Check whether user-given URL is a calendar collection and/or contains <calendar-home-set> and/or has <current-user-principal>"); DavResource davBase = new DavResource(log, httpClient, userURL); try { if (service == Service.CALDAV) { davBase.propfind(0, CalendarHomeSet.NAME, SupportedCalendarComponentSet.NAME, ResourceType.NAME, DisplayName.NAME, CalendarColor.NAME, CalendarDescription.NAME, CalendarTimezone.NAME, CurrentUserPrivilegeSet.NAME, CurrentUserPrincipal.NAME); addIfCalendar(davBase); } else if (service == Service.CARDDAV) { davBase.propfind(0, AddressbookHomeSet.NAME, ResourceType.NAME, DisplayName.NAME, AddressbookDescription.NAME, CurrentUserPrivilegeSet.NAME, CurrentUserPrincipal.NAME); addIfAddressBook(davBase); } } catch (IOException | HttpException | DavException e) { log.debug("PROPFIND on user-given URL failed", e); } if (service == Service.CALDAV) { CalendarHomeSet calendarHomeSet = (CalendarHomeSet) davBase.properties.get(CalendarHomeSet.NAME); if (calendarHomeSet != null) { log.info("Found <calendar-home-set> at user-given URL"); for (String href : calendarHomeSet.hrefs) { HttpUrl url = userURL.resolve(href); if (url != null) homeSets.add(url); } } } else if (service == Service.CARDDAV) { AddressbookHomeSet addressbookHomeSet = (AddressbookHomeSet) davBase.properties .get(AddressbookHomeSet.NAME); if (addressbookHomeSet != null) { log.info("Found <addressbook-home-set> at user-given URL"); for (String href : addressbookHomeSet.hrefs) { HttpUrl url = userURL.resolve(href); if (url != null) homeSets.add(url); } } } /* When home sets haven already been found, skip further searching. * Otherwise (no home sets found), treat the user-given URL as "initial context path" for service discovery. * * Keep in mind that the CalDAV principal URL must not be the CardDAV principal URL! */ if (homeSets.isEmpty()) try { log.info("No home sets found, looking for <current-user-principal>"); davBase.options(); if ((service == Service.CALDAV && davBase.capabilities.contains("calendar-access")) || (service == Service.CARDDAV && davBase.capabilities.contains("addressbook"))) { CurrentUserPrincipal currentUserPrincipal = (CurrentUserPrincipal) davBase.properties .get(CurrentUserPrincipal.NAME); if (currentUserPrincipal != null && currentUserPrincipal.href != null) principalUrl = davBase.location.resolve(currentUserPrincipal.href); } } catch (IOException | HttpException | DavException e) { log.debug("Couldn't find <current-user-principal> at user-given URL", e); } if (principalUrl == null) try { log.info("User-given URL doesn't contain <current-user-principal>, trying /.well-known/" + service.name); principalUrl = getCurrentUserPrincipal(userURL.resolve("/.well-known/" + service.name)); } catch (IOException | HttpException | DavException e) { log.debug("Couldn't determine <current-user-principal> from well-known " + service + " path", e); } if (principalUrl == null) // still no principal URL, try service discovery with "domain" = user-given host name domain = baseURI.getHost(); } else if ("mailto".equals(baseURI.getScheme())) { String mailbox = baseURI.getSchemeSpecificPart(); // determine service FQDN int posAt = mailbox.lastIndexOf("@"); if (posAt == -1) throw new URISyntaxException(mailbox, "Missing @ sign"); domain = mailbox.substring(posAt + 1); } if (principalUrl == null && domain != null) { log.info("No principal URL yet, trying SRV/TXT records with domain " + domain); try { principalUrl = discoverPrincipalUrl(domain, service); } catch (IOException | HttpException | DavException e) { log.info("Couldn't find principal URL using service discovery"); } } // principal URL has been found, get addressbook-home-set/calendar-home-set if (principalUrl != null) { log.info("Principal URL=" + principalUrl + ", getting <calendar-home-set>"); try { DavResource principal = new DavResource(log, httpClient, principalUrl); if (service == Service.CALDAV) { principal.propfind(0, CalendarHomeSet.NAME); CalendarHomeSet calendarHomeSet = (CalendarHomeSet) principal.properties .get(CalendarHomeSet.NAME); if (calendarHomeSet != null) { log.info("Found <calendar-home-set> at principal URL"); for (String href : calendarHomeSet.hrefs) { HttpUrl url = principal.location.resolve(href); if (url != null) homeSets.add(url); } } } else if (service == Service.CARDDAV) { principal.propfind(0, AddressbookHomeSet.NAME); AddressbookHomeSet addressbookHomeSet = (AddressbookHomeSet) principal.properties .get(AddressbookHomeSet.NAME); if (addressbookHomeSet != null) { log.info("Found <addressbook-home-set> at principal URL"); for (String href : addressbookHomeSet.hrefs) { HttpUrl url = principal.location.resolve(href); if (url != null) homeSets.add(url); } } } } catch (IOException | HttpException | DavException e) { log.debug("PROPFIND on " + principalUrl + " failed", e); } } // now query all home sets for (HttpUrl url : homeSets) if (service == Service.CALDAV) try { log.info("Listing calendar collections in home set " + url); DavResource homeSet = new DavResource(log, httpClient, url); homeSet.propfind(1, SupportedCalendarComponentSet.NAME, ResourceType.NAME, DisplayName.NAME, CurrentUserPrivilegeSet.NAME, CalendarColor.NAME, CalendarDescription.NAME, CalendarTimezone.NAME); // home set should not be a calendar, but some servers have only one calendar and it's the home set addIfCalendar(homeSet); // members of the home set can be calendars, too for (DavResource member : homeSet.members) addIfCalendar(member); } catch (IOException | HttpException | DavException e) { log.debug("PROPFIND on " + url + " failed", e); } else if (service == Service.CARDDAV) try { log.info("Listing address books in home set " + url); DavResource homeSet = new DavResource(log, httpClient, url); homeSet.propfind(1, ResourceType.NAME, DisplayName.NAME, CurrentUserPrivilegeSet.NAME, AddressbookDescription.NAME); // home set should not be an address book, but some servers have only one address book and it's the home set addIfAddressBook(homeSet); // members of the home set can be calendars, too for (DavResource member : homeSet.members) addIfAddressBook(member); } catch (IOException | HttpException | DavException e) { log.debug("PROPFIND on " + url + " failed", e); } if (service == Service.CALDAV) { serverInfo.setCalendars(calendars.values().toArray(new ServerInfo.ResourceInfo[calendars.size()])); serverInfo.setTaskLists(taskLists.values().toArray(new ServerInfo.ResourceInfo[taskLists.size()])); } else if (service == Service.CARDDAV) serverInfo.setAddressBooks( addressbooks.values().toArray(new ServerInfo.ResourceInfo[addressbooks.size()])); }
From source file:io.fabric8.kubernetes.client.dsl.base.BaseOperation.java
License:Apache License
public L list() throws KubernetesClientException { try {/*w w w .ja v a 2s . c o m*/ HttpUrl.Builder requestUrlBuilder = HttpUrl.get(getNamespacedUrl()).newBuilder(); String labelQueryParam = getLabelQueryParam(); if (labelQueryParam.length() > 0) { requestUrlBuilder.addQueryParameter("labelSelector", labelQueryParam); } String fieldQueryString = getFieldQueryParam(); if (fieldQueryString.length() > 0) { requestUrlBuilder.addQueryParameter("fieldSelector", fieldQueryString); } Request.Builder requestBuilder = new Request.Builder().get().url(requestUrlBuilder.build()); return handleResponse(requestBuilder, 200, listType); } catch (InterruptedException | ExecutionException | IOException e) { throw KubernetesClientException.launderThrowable(e); } }
From source file:io.fabric8.kubernetes.client.dsl.internal.WatchConnectionManager.java
License:Apache License
private final void runWatch() throws MalformedURLException, ExecutionException, InterruptedException { URL requestUrl = baseOperation.getNamespacedUrl(); HttpUrl.Builder httpUrlBuilder = HttpUrl.get(requestUrl).newBuilder(); String labelQueryParam = baseOperation.getLabelQueryParam(); if (labelQueryParam.length() > 0) { httpUrlBuilder.addQueryParameter("labelSelector", labelQueryParam); }/*from ww w . j a v a 2 s .c om*/ String fieldQueryString = baseOperation.getFieldQueryParam(); String name = baseOperation.getName(); if (name != null && name.length() > 0) { if (fieldQueryString.length() > 0) { fieldQueryString += ","; } fieldQueryString += "metadata.name=" + name; } httpUrlBuilder.addQueryParameter("fieldSelector", fieldQueryString); httpUrlBuilder.addQueryParameter("resourceVersion", this.resourceVersion.get()).addQueryParameter("watch", "true"); Request request = new Request.Builder().get().url(httpUrlBuilder.build()) .addHeader("Origin", requestUrl.getProtocol() + "://" + requestUrl.getHost() + ":" + requestUrl.getPort()) .build(); clonedClient.setReadTimeout(0, TimeUnit.MILLISECONDS); webSocketCall = WebSocketCall.create(clonedClient, request); webSocketCall.enqueue(new WebSocketListener() { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public void onOpen(WebSocket webSocket, Response response) { webSocketRef.set(webSocket); currentReconnectAttempt.set(0); } @Override public void onFailure(IOException e, Response response) { e.printStackTrace(); try { if (response != null && response.body() != null) { response.body().close(); } } catch (IOException e1) { e1.printStackTrace(); } if (forceClosed.get()) { executor.shutdownNow(); watcher.onClose(null); return; } onClose(4000, "Connection unexpectedly closed"); } @Override public void onMessage(ResponseBody message) throws IOException { try { WatchEvent event = mapper.readValue(message.byteStream(), WatchEvent.class); T obj = (T) event.getObject(); //Dirty cast - should always be valid though String currentResourceVersion = resourceVersion.get(); String newResourceVersion = ((HasMetadata) obj).getMetadata().getResourceVersion(); if (currentResourceVersion.compareTo(newResourceVersion) < 0) { resourceVersion.compareAndSet(currentResourceVersion, newResourceVersion); } Watcher.Action action = Watcher.Action.valueOf(event.getType()); watcher.eventReceived(action, obj); } catch (IOException e) { logger.error("Could not deserialize watch event: {}", message.source().readUtf8(), e); } catch (ClassCastException e) { logger.error("Received wrong type of object for watch", e); } catch (IllegalArgumentException e) { logger.error("Invalid event type", e); } finally { message.close(); } } @Override public void onPong(Buffer buffer) { } @Override public void onClose(final int code, final String reason) { if (forceClosed.get()) { executor.shutdownNow(); watcher.onClose(null); return; } executor.submit(new Runnable() { @Override public void run() { try { runWatch(); } catch (ExecutionException e) { if (e.getCause() != null && e.getCause().getCause() != null && e.getCause().getCause() instanceof ConnectException) { if (reconnectLimit >= 0 && currentReconnectAttempt.getAndIncrement() >= reconnectLimit) { watcher.onClose( new KubernetesClientException("Connection unexpectedly closed", e)); return; } try { TimeUnit.MILLISECONDS.sleep(reconnectInterval); } catch (InterruptedException e1) { watcher.onClose( new KubernetesClientException("Connection unexpectedly closed", e1)); return; } onClose(code, reason); } } catch (MalformedURLException | InterruptedException e) { throw KubernetesClientException.launderThrowable(e); } } }); } }); }
From source file:org.bitcoinj_extra.net.discovery.HttpDiscovery.java
License:Apache License
@Override public InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException { try {/*from w ww.j a va2 s. c o m*/ HttpUrl.Builder url = HttpUrl.get(details.uri).newBuilder(); if (services != 0) url.addQueryParameter("srvmask", Long.toString(services)); Request.Builder request = new Request.Builder(); request.url(url.build()); request.addHeader("User-Agent", VersionMessage.LIBRARY_SUBVER); // TODO Add main version. log.info("Requesting seeds from {}", url); Response response = client.newCall(request.build()).execute(); if (!response.isSuccessful()) throw new PeerDiscoveryException( "HTTP request failed: " + response.code() + " " + response.message()); InputStream stream = response.body().byteStream(); GZIPInputStream zip = new GZIPInputStream(stream); PeerSeedProtos.SignedPeerSeeds proto = PeerSeedProtos.SignedPeerSeeds.parseDelimitedFrom(zip); stream.close(); return protoToAddrs(proto); } catch (PeerDiscoveryException e1) { throw e1; } catch (Exception e) { throw new PeerDiscoveryException(e); } }
From source file:org.mariotaku.twidere.util.OAuthPasswordAuthenticator.java
License:Open Source License
public OAuthPasswordAuthenticator(final TwitterOAuth oauth, final LoginVerificationCallback loginVerificationCallback, final String userAgent) { final RestClient restClient = RestAPIFactory.getRestClient(oauth); this.oauth = oauth; this.client = (OkHttpRestClient) restClient.getRestClient(); final OkHttpClient okhttp = client.getClient(); okhttp.setCookieHandler(new CookieManager()); okhttp.networkInterceptors().add(new Interceptor() { @Override//from w w w .ja va 2s .co m public Response intercept(Chain chain) throws IOException { final Response response = chain.proceed(chain.request()); if (!response.isRedirect()) { return response; } final String location = response.header("Location"); final Response.Builder builder = response.newBuilder(); if (!TextUtils.isEmpty(location) && !endpoint.checkEndpoint(location)) { final HttpUrl originalLocation = HttpUrl .get(URI.create("https://api.twitter.com/").resolve(location)); final HttpUrl.Builder locationBuilder = HttpUrl.parse(endpoint.getUrl()).newBuilder(); for (String pathSegments : originalLocation.pathSegments()) { locationBuilder.addPathSegment(pathSegments); } for (int i = 0, j = originalLocation.querySize(); i < j; i++) { final String name = originalLocation.queryParameterName(i); final String value = originalLocation.queryParameterValue(i); locationBuilder.addQueryParameter(name, value); } final String encodedFragment = originalLocation.encodedFragment(); if (encodedFragment != null) { locationBuilder.encodedFragment(encodedFragment); } final HttpUrl newLocation = locationBuilder.build(); builder.header("Location", newLocation.toString()); } return builder.build(); } }); this.endpoint = restClient.getEndpoint(); this.loginVerificationCallback = loginVerificationCallback; this.userAgent = userAgent; }