public static String c(String str) { if (TextUtils.isEmpty(str)) { return str; } URI i = i(str); if (i == null) { return str; } i = i.normalize(); if (i.isOpaque()) { return str; } i = URIUtils.resolve(i, "./"); if (i != null) { return i.toString(); } return str; }
/** Return final location from http redirects */ public static String resolveHttpRedirects(String uri) throws IOException, URISyntaxException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpClientContext context = HttpClientContext.create(); HttpGet httpget = new HttpGet(uri); //httpget.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/20121202 Firefox/17.0 Iceweasel/17.0.1"); CloseableHttpResponse response = httpclient.execute(httpget, context); try { HttpHost target = context.getTargetHost(); List<URI> redirectLocations = context.getRedirectLocations(); URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations); return location.toString(); } finally { response.close(); } }
public OTSUri(String endpoint, String action) { this.action = action; final String delimiter = "/"; if (!endpoint.endsWith(delimiter)) { endpoint += delimiter; } // keep only one '/' in the end int index = endpoint.length() - 1; while (index > 0 && endpoint.charAt(index - 1) == '/') { index--; } endpoint = endpoint.substring(0, index + 1); try { this.uri = new URI(endpoint + action); } catch (URISyntaxException e) { throw new IllegalArgumentException("The endpoint is invalid.", e); } this.host = URIUtils.extractHost(uri); }
static void rewriteRequestURI( final HttpRequestWrapper request, final HttpRoute route) throws ProtocolException { try { URI uri = request.getURI(); if (uri != null) { // Make sure the request URI is relative if (uri.isAbsolute()) { uri = URIUtils.rewriteURI(uri, null, true); } else { uri = URIUtils.rewriteURI(uri); } request.setURI(uri); } } catch (final URISyntaxException ex) { throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex); } }
/** * Creates absolute request URI with full path from passed in context. */ @Nonnull private URI getRequestURI(final HttpContext context) { final HttpClientContext clientContext = HttpClientContext.adapt(context); final HttpRequest httpRequest = clientContext.getRequest(); final HttpHost target = clientContext.getTargetHost(); try { URI uri; if (httpRequest instanceof HttpUriRequest) { uri = ((HttpUriRequest) httpRequest).getURI(); } else { uri = URI.create(httpRequest.getRequestLine().getUri()); } return uri.isAbsolute() ? uri : URIUtils.resolve(URI.create(target.toURI()), uri); } catch (Exception e) { log.warn("Could not create absolute request URI", e); return URI.create(target.toURI()); } }
/** * @param query * e.g. "/issues.xml" * @return URI with auth parameter "key" if not in "basic auth mode. */ private URI createURI(String query, Collection<? extends NameValuePair> origParams) { final List<NameValuePair> params = new ArrayList<NameValuePair>( origParams); if (apiAccessKey != null) { params.add(new BasicNameValuePair("key", apiAccessKey)); } URI uri; try { URL url = baseURL; String path = url.getPath(); if (!query.isEmpty()) { path += "/" + query; } uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), path, URLEncodedUtils.format(params, "UTF-8"), null); } catch (URISyntaxException e) { throw new RedmineInternalError(e); } return uri; }
protected void initTarget() throws ServletException { // TODO - should get the Kibana URI from Settings.java // targetUri = Settings.getKibanaUri(); targetUri = settings.getYarnWebUIAddress(); if (!targetUri.contains("http://")) { targetUri = "http://" + targetUri; } if (targetUri == null) { throw new ServletException(P_TARGET_URI + " is required."); } //test it's valid try { targetUriObj = new URI(targetUri); } catch (Exception e) { throw new ServletException("Trying to process targetUri init parameter: " + e, e); } targetHost = URIUtils.extractHost(targetUriObj); }
protected void initTarget() throws ServletException { // TODO - should get the Kibana URI from Settings.java // targetUri = Settings.getKibanaUri(); targetUri = getConfigParam(P_TARGET_URI); if (targetUri == null) { throw new ServletException(P_TARGET_URI + " is required."); } //test it's valid try { targetUriObj = new URI(targetUri); } catch (Exception e) { throw new ServletException("Trying to process targetUri init parameter: " + e, e); } targetHost = URIUtils.extractHost(targetUriObj); }
/** * Make a GET request and append the Map of parameters onto the query string. * @param address the fully qualified URL to make the request to * @param parameters the Map of parameters, ie key,value pairs * @return */ private String doGet(String address, Map<String, String> parameters){ try { List<NameValuePair> queryParams = new ArrayList<NameValuePair>(); for (Map.Entry<String,String> entry : parameters.entrySet()) { queryParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } URI uri = URIUtils.createURI(null, address, -1, null, URLEncodedUtils.format(queryParams, "UTF-8"), null); log.info(uri.toString()); return doGet(uri.toString()); } catch (URISyntaxException e) { log.error(e.getClass() + ":" + e.getMessage()); } return null; }
/** * @since 4.1 */ protected URI createLocationURI(final String location) throws ProtocolException { try { URI uri; //NULogger.getLogger().log(Level.INFO, "location: {0}", location); //If it contains a special char we create our custom uri (it fails otherwise) if(location.contains("|")){ uri = neembuu.uploader.utils.URIUtils.createURI(location); } else{ uri = new URI(location); } return uri.normalize(); } catch (URISyntaxException ex) { throw new ProtocolException("Invalid redirect URI: " + location, ex); } }
protected void rewriteRequestURI( final RequestWrapper request, final HttpRoute route) throws ProtocolException { try { URI uri = request.getURI(); if (route.getProxyHost() != null && !route.isTunnelled()) { // Make sure the request URI is absolute if (!uri.isAbsolute()) { HttpHost target = route.getTargetHost(); uri = URIUtils.rewriteURI(uri, target); request.setURI(uri); } } else { // Make sure the request URI is relative if (uri.isAbsolute()) { uri = URIUtils.rewriteURI(uri, null); request.setURI(uri); } } } catch (URISyntaxException ex) { throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex); } }
@Override protected ArrayList<? extends IListItem> loadTopics(Client client, ListInfo listInfo) throws IOException, ParseException, URISyntaxException { SharedPreferences prefs = App.getInstance().getPreferences(); if (mUrl == null) { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("showforum", getForumId())); qparams.add(new BasicNameValuePair("sort_key", prefs.getString(getListName() + ".sort_key", "last_post"))); qparams.add(new BasicNameValuePair("sort_by", prefs.getString(getListName() + ".sort_by", "Z-A"))); qparams.add(new BasicNameValuePair("prune_day", prefs.getString(getListName() + ".prune_day", "100"))); qparams.add(new BasicNameValuePair("topicfilter", prefs.getString(getListName() + ".topicfilter", "all"))); qparams.add(new BasicNameValuePair("st", Integer.toString(listInfo.getFrom()))); URI uri = URIUtils.createURI("http", "4pda.ru", -1, "/forum/index.php", URLEncodedUtils.format(qparams, "UTF-8"), null); mUrl = uri.toString(); } else { mUrl = mUrl.replaceAll("&st=\\d+", "").concat("&st=" + mListInfo.getFrom()); } ArrayList<Topic> res = TopicsApi.getForumTopics(client, mUrl,getForumId(), prefs.getBoolean(getListName() + ".unread_in_top", false), mListInfo); mUrl = Client.getInstance().getRedirectUri() != null ? Client.getInstance().getRedirectUri().toString() : mUrl; return res; }
public static String pinFavorite(IHttpClient httpClient, String topicId, String trackType) throws ParseException, IOException, URISyntaxException { FavTopic favTopic = findTopicInFav(httpClient, topicId); if (favTopic == null) { return "Тема не найдена в избранном"; } List<NameValuePair> qparams = new ArrayList<>(); qparams.add(new BasicNameValuePair("act", "fav")); qparams.add(new BasicNameValuePair("selectedtids", favTopic.getTid())); qparams.add(new BasicNameValuePair("tact", trackType)); URI uri = URIUtils.createURI("http", "4pda.ru", -1, "/forum/index.php", URLEncodedUtils.format(qparams, "UTF-8"), null); httpClient.performGet(uri.toString()); return TRACK_TYPE_PIN.equals(trackType) ? "Тема закреплена" : "Тема откреплена"; }
public static String getAllScoresFromServer(String serverIP, int serverPort) throws URISyntaxException, IOException { URI uri = URIUtils.createURI("http", serverIP, serverPort, "/getScores", null, null); URL url = uri.toURL(); URLConnection conn = url.openConnection(); InputStream is = conn.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer); String response = writer.toString(); JSONObject jsonObject = new JSONObject(response); System.out.println(response); return jsonObject.toString(); }
protected static MDSResult doPost(String scheme, String host, int port, String path, List<NameValuePair> postData) throws UnsupportedEncodingException{ URI uri = null; try { uri = URIUtils.createURI(scheme, host, port, path, null, null); } catch (URISyntaxException e) { e.printStackTrace(); throw new IllegalArgumentException(String.format("Can not post to mds: %s, %s, %d, %s", scheme,host,port,path),e); } Log.d(TAG, "doPost() uri: " + uri.toASCIIString()); HttpPost post = new HttpPost(uri); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, "UTF-8"); post.setEntity(entity); return MDSInterface2.doExecute(post); }
protected static MDSResult doPost(String scheme, String host, int port, String path, HttpEntity entity) { URI uri = null; try { uri = URIUtils.createURI(scheme, host, port, path, null, null); } catch (URISyntaxException e) { e.printStackTrace(); throw new IllegalArgumentException(String.format("Can not post to mds: %s, %s, %d, %s", scheme,host,port,path),e); } Log.d(TAG, "doPost() uri: " + uri.toASCIIString()); HttpPost post = new HttpPost(uri); post.setEntity(entity); return MDSInterface2.doExecute(post); }
@Override public ResponseEntity<byte[]> fetchFileFromCdr(UserFile file, String remoteFileUrl) throws FileNotAvailableException, URISyntaxException { HttpHeaders authorization = new HttpHeaders(); // use user provided auth info only when the remote file is in the same host as UserFile. if (URIUtils.extractHost(new URI(remoteFileUrl)).equals(URIUtils.extractHost(new URI(file.getEnvelope())))) { authorization = getAuthorizationHeader(file); } ResponseEntity<byte[]> download = null; try { download = restOperations .exchange(new URI(remoteFileUrl), HttpMethod.GET, new HttpEntity<Object>(authorization), byte[].class); } catch (RestClientException e) { LOGGER.error("Unable to download remote file.", e); } if (download == null || !download.hasBody()) { throw new FileNotAvailableException("Response is not OK or body not attached for " + remoteFileUrl); } return download; }
@Override public InputStream getInputStream() throws IOException { try { int port = m_url.getPort() > 0 ? m_url.getPort() : m_url.getDefaultPort(); String[] userInfo = m_url.getUserInfo() == null ? null : m_url.getUserInfo().split(":"); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(URIUtils.createURI(m_url.getProtocol(), m_url.getHost(), port, m_url.getPath(), m_url.getQuery(), null)); if (userInfo != null) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userInfo[0], userInfo[1]); request.addHeader(BasicScheme.authenticate(credentials, "UTF-8", false)); } HttpResponse response = client.execute(request); return new ByteArrayInputStream(EntityUtils.toByteArray(response.getEntity())); } catch (Exception e) { throw new IOException("Can't retrieve " + m_url.getPath() + " from " + m_url.getHost() + " because " + e.getMessage()); } }
public void setQueryParameters(List<NameValuePair> parms) { URI uri = this.getURI(); URI uriWithQueryString = null; try { String query = URLEncodedUtils.format(parms, "UTF-8"); uriWithQueryString = URIUtils.createURI( uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(), // Do we need to merge any existing query params? // Probably not... shouldn't be any. query, uri.getFragment() ); this.setURI(uriWithQueryString); } catch (URISyntaxException e) { ThreadCategory.getInstance("Cannot add query parameters to URI: " + this.getClass()).warn(e.getMessage(), e); } }
public void createSession(String alias, String url, Map<String, String> headers, Authentication auth, String verify, Boolean debug, String loggerClass, String password, boolean verifyHost, boolean selfSigned, Proxy proxy) { HostnameVerifier defaultHostnameVerifier = verifyHost ? null : NoopHostnameVerifier.INSTANCE; TrustStrategy trustStrategy = selfSigned ? new TrustSelfSignedStrategy() : null; if (!loggerClass.isEmpty()) { System.setProperty("org.apache.commons.logging.Log", loggerClass); System.setProperty("org.apache.commons.logging.robotlogger.log.org.apache.http", debug ? "DEBUG" : "INFO"); } HttpHost target; try { target = URIUtils.extractHost(new URI(url)); } catch (URISyntaxException e) { throw new RuntimeException("Parsing of URL failed. Error message: " + e.getMessage()); } Session session = new Session(); session.setProxy(proxy); session.setContext(this.createContext(auth, target)); session.setClient(this.createHttpClient(auth, verify, target, false, password, null, null, proxy)); session.setUrl(url); session.setHeaders(headers); session.setHttpHost(target); session.setVerify(verify); session.setAuthentication(auth); session.setPassword(password); session.setHostnameVerifier(defaultHostnameVerifier); session.setTrustStrategy(trustStrategy); sessions.put(alias, session); }
@org.junit.Test public void testUri() throws Exception{ String param = "param1=" + URLEncoder.encode("中国", "UTF-8") + "¶m2=value2"; URI uri = URIUtils.createURI("http", "localhost", 8080, "/sshsky/index.html", param, null); System.out.println(uri); }
@Override protected void before() throws Throwable { final SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(5000).build(); serverBootstrap = ServerBootstrap.bootstrap().setSocketConfig(socketConfig).setServerInfo(ORIGIN); if(ProtocolScheme.https.equals(protocolScheme)) { serverBootstrap.setSslContext(SSLTestContexts.createServerSSLContext()); } registerHandlers(); server = serverBootstrap.create(); server.start(); host = new HttpHost("127.0.0.1", server.getLocalPort(), protocolScheme.name()); uri = URIUtils.rewriteURI(new URI("/"), host); }
public static HttpHost determineTarget(final HttpUriRequest request) throws ClientProtocolException { // A null target may be acceptable if there is a default target. // Otherwise, the null target is detected in the director. HttpHost target = null; final URI requestURI = request.getURI(); if (requestURI.isAbsolute()) { target = URIUtils.extractHost(requestURI); if (target == null) { throw new ClientProtocolException("URI does not specify a valid host name: " + requestURI); } } return target; }
private static HttpHost determineTarget(HttpUriRequest request) throws ClientProtocolException { // A null target may be acceptable if there is a default target. // Otherwise, the null target is detected in the director. HttpHost target = null; URI requestURI = request.getURI(); if (requestURI.isAbsolute()) { target = URIUtils.extractHost(requestURI); if (target == null) { throw new ClientProtocolException( "URI does not specify a valid host name: " + requestURI); } } return target; }
protected void rewriteRequestURI( final RequestWrapper request, final HttpRoute route) throws ProtocolException { try { URI uri = request.getURI(); if (route.getProxyHost() != null && !route.isTunnelled()) { // Make sure the request URI is absolute if (!uri.isAbsolute()) { HttpHost target = route.getTargetHost(); uri = URIUtils.rewriteURI(uri, target, true); } else { uri = URIUtils.rewriteURI(uri); } } else { // Make sure the request URI is relative if (uri.isAbsolute()) { uri = URIUtils.rewriteURI(uri, null); } else { uri = URIUtils.rewriteURI(uri); } } request.setURI(uri); } catch (URISyntaxException ex) { throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex); } }
@Override public Future<BanResponse> getActiveBan(UUID serverUuid, String playerIdentifier) { HttpGet httpRequest = new HttpGet(buildSafe(createUri("/server/" + serverUuid + "/check/" + escape(playerIdentifier)))); initHeaders(httpRequest); return client.execute( new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest), SerializerConsumer.create(config.getSerializer(), BanResponse.class), DeafFutureCallback.<BanResponse>instance() ); }
@Override public Future<BanResponse> createBan(BanRequest request) { HttpPost httpRequest = new HttpPost(buildSafe(createUri("/bans"))); initHeaders(httpRequest); httpRequest.setEntity(createEntity(request)); return client.execute( new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest), SerializerConsumer.create(config.getSerializer(), BanResponse.class), DeafFutureCallback.<BanResponse>instance() ); }
@Override public Future<BanResponse> updateBan(BanRequest request) { HttpPut httpRequest = new HttpPut(buildSafe(createUri("/ban/" + request.getId()))); initHeaders(httpRequest); httpRequest.setEntity(createEntity(request)); return client.execute( new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest), SerializerConsumer.create(config.getSerializer(), BanResponse.class), DeafFutureCallback.<BanResponse>instance() ); }
@Override public Future<BanResponse> deleteBan(UUID banId) { HttpDelete httpRequest = new HttpDelete(buildSafe(createUri("/ban/" + banId))); initHeaders(httpRequest); return client.execute( new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest), SerializerConsumer.create(config.getSerializer(), BanResponse.class), DeafFutureCallback.<BanResponse>instance() ); }
@Override public Future<NoticeResponse> createNotice(NoticeRequest request) { HttpPost httpRequest = new HttpPost(buildSafe(createUri("/notices"))); initHeaders(httpRequest); httpRequest.setEntity(createEntity(request)); return client.execute( new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest), SerializerConsumer.create(config.getSerializer(), NoticeResponse.class), DeafFutureCallback.<NoticeResponse>instance() ); }
@Override public Future<NoticeResponse> updateNotice(NoticeRequest request) { HttpPut httpRequest = new HttpPut(buildSafe(createUri("/notice/" + request.getId()))); initHeaders(httpRequest); httpRequest.setEntity(createEntity(request)); return client.execute( new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest), SerializerConsumer.create(config.getSerializer(), NoticeResponse.class), DeafFutureCallback.<NoticeResponse>instance() ); }
@Override public Future<NoticeResponse> deleteNotice(UUID noticeId) { HttpDelete httpRequest = new HttpDelete(buildSafe(createUri("/notice/" + noticeId))); initHeaders(httpRequest); return client.execute( new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest), SerializerConsumer.create(config.getSerializer(), NoticeResponse.class), DeafFutureCallback.<NoticeResponse>instance() ); }
@Override public Future<KickResponse> kick(KickRequest request) { HttpPost httpRequest = new HttpPost(buildSafe(createUri("/kick"))); initHeaders(httpRequest); httpRequest.setEntity(createEntity(request)); return client.execute( new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest), SerializerConsumer.create(config.getSerializer(), KickResponse.class), DeafFutureCallback.<KickResponse>instance() ); }
@Override public Future<ServerHeartbeatResponse> doHeartbeat(ServerHeartbeatRequest request) { HttpPost httpRequest = new HttpPost(buildSafe(createUri("/server/heartbeat"))); initHeaders(httpRequest); httpRequest.setEntity(createEntity(request)); return client.execute( new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest), SerializerConsumer.create(config.getSerializer(), ServerHeartbeatResponse.class), DeafFutureCallback.<ServerHeartbeatResponse>instance() ); }