List of usage examples for org.apache.http.client.utils URIBuilder build
public URI build() throws URISyntaxException
From source file:org.dbrane.cloud.util.httpclient.HttpClientHelper.java
public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params) { try {//from w ww .j a v a 2 s . co m URIBuilder ub = new URIBuilder(); ub.setPath(url); ArrayList<NameValuePair> pairs = covertParams2NVPS(params); ub.setParameters(pairs); HttpGet httpGet = new HttpGet(ub.build()); for (Map.Entry<String, Object> param : headers.entrySet()) { httpGet.addHeader(param.getKey(), String.valueOf(param.getValue())); } return getResult(httpGet); } catch (Exception e) { logger.debug(ErrorType.Httpclient.toString(), e); throw new BaseException(ErrorType.Httpclient, e); } }
From source file:org.wso2.carbon.appmgt.mdm.restconnector.utils.RestUtils.java
/** * If not exists generate new access key or return existing one. * * @param remoteServer bean that holds information about remote server * @param generateNewKey whether generate new access key or not * @return generated access key//w w w .jav a 2s . co m */ public static String getAPIToken(RemoteServer remoteServer, boolean generateNewKey) { if (!generateNewKey) { if (!(AuthHandler.authKey == null || "null".equals(AuthHandler.authKey))) { return AuthHandler.authKey; } } HttpClient httpClient = AppManagerUtil.getHttpClient(remoteServer.getTokenApiURL()); HttpPost postMethod = null; HttpResponse response = null; String responseString = ""; try { List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add( new BasicNameValuePair(Constants.RestConstants.GRANT_TYPE, Constants.RestConstants.PASSWORD)); nameValuePairs .add(new BasicNameValuePair(Constants.RestConstants.USERNAME, remoteServer.getAuthUser())); nameValuePairs .add(new BasicNameValuePair(Constants.RestConstants.PASSWORD, remoteServer.getAuthPass())); URIBuilder uriBuilder = new URIBuilder(remoteServer.getTokenApiURL()); uriBuilder.addParameters(nameValuePairs); postMethod = new HttpPost(uriBuilder.build()); postMethod.setHeader(Constants.RestConstants.AUTHORIZATION, Constants.RestConstants.BASIC + new String(Base64.encodeBase64((remoteServer.getClientKey() + Constants.RestConstants.COLON + remoteServer.getClientSecret()).getBytes()))); postMethod.setHeader(Constants.RestConstants.CONTENT_TYPE, Constants.RestConstants.APPLICATION_FORM_URL_ENCODED); } catch (URISyntaxException e) { String errorMessage = "Cannot construct the Httppost. Url Encoded error."; log.error(errorMessage, e); return null; } try { if (log.isDebugEnabled()) { log.debug("Sending POST request to API Token endpoint. Request path: " + remoteServer.getTokenApiURL()); } response = httpClient.execute(postMethod); int statusCode = response.getStatusLine().getStatusCode(); if (log.isDebugEnabled()) { log.debug("Status code " + statusCode + " received while accessing the API Token endpoint."); } } catch (IOException e) { String errorMessage = "Cannot connect to Token API Endpoint."; log.error(errorMessage, e); return null; } try { HttpEntity entity = response.getEntity(); if (entity != null) { responseString = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); } } catch (IOException e) { String errorMessage = "Cannot get response body for auth."; log.error(errorMessage, e); return null; } JSONObject token = (JSONObject) new JSONValue().parse(responseString); AuthHandler.authKey = String.valueOf(token.get(Constants.RestConstants.ACCESS_TOKEN)); return AuthHandler.authKey; }
From source file:com.ecofactor.qa.automation.util.HttpsUtil.java
/** * Gets the.//from w ww . j av a 2 s. c om * @param url the url * @return the https response */ public static String get(String url, Map<String, String> params, int expectedStatus) { String content = null; HttpGet request = new HttpGet(url); URIBuilder builder = new URIBuilder(request.getURI()); if (params != null) { Set<String> keys = params.keySet(); for (String key : keys) { builder.addParameter(key, params.get(key)); } } try { request.setURI(builder.build()); DriverConfig.setLogString("URL " + request.getURI().toString(), true); driver.navigate().to(request.getURI().toString()); tinyWait(); content = driver.findElement(By.tagName("Body")).getText(); DriverConfig.setLogString("Content: " + content, true); } catch (Exception e) { LOGGER.error(e.getMessage()); } finally { request.releaseConnection(); } return content; }
From source file:de.bmarwell.j9kwsolver.util.RequestToURI.java
/** * Sends Accept to the 9kw Captcha Service. * @param cno the CaptchaNewOk Object for API request. * @return the URI for the API request.//from ww w .j a v a 2 s. c o m */ public static URI captchaNewOkToURI(final CaptchaNewOk cno) { URI uri = null; URI apiURI = stringToURI(cno.getUrl()); URIBuilder builder = new URIBuilder(apiURI).addParameter("action", cno.getAction()) .addParameter("apikey", cno.getApikey()).addParameter("source", cno.getSource()); try { uri = builder.build(); } catch (URISyntaxException e) { LOG.error("Konnte URI nicht erstellen!", e); } return uri; }
From source file:org.sentilo.common.utils.URIUtils.java
public static String getURI(final String host, final String path, final RequestParameters parameters) { try {/*from w w w .j ava 2 s .com*/ final URI baseURI = getBaseURI(host, path); final URIBuilder builder = new URIBuilder(baseURI); if (parameters != null && parameters.size() > 0) { for (final String key : parameters.keySet()) { final String value = parameters.get(key); builder.setParameter(key, value); } } return builder.build().toString(); } catch (final URISyntaxException e) { throw buildIllegalArgumentException(host, path, e); } }
From source file:org.hl7.fhir.client.ResourceAddress.java
public static URI buildEndpointUriFromString(String endpointPath) { URI uri = null;// ww w . j a va2 s . c om try { URIBuilder uriBuilder = new URIBuilder(endpointPath); uri = uriBuilder.build(); String scheme = uri.getScheme(); String host = uri.getHost(); if (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https")) { throw new EFhirClientException("Scheme must be 'http' or 'https': " + uri); } if (StringUtils.isBlank(host)) { throw new EFhirClientException("host cannot be blank: " + uri); } } catch (URISyntaxException e) { throw new EFhirClientException("Invalid URI", e); } return uri; }
From source file:com.peteydog7.mcstreamnotifier.twitch.Http.java
public static String sendApiGet(String urlPath, List<NameValuePair> urlParameters) throws Exception { if (Config.Value.AUTH_TOKEN != "none") { urlParameters.add(new BasicNameValuePair("oauth_token", Config.Value.AUTH_TOKEN)); }/*w w w. j a va 2 s. co m*/ URIBuilder uriBuilder = new URIBuilder(); uriBuilder.setScheme("https"); uriBuilder.setHost(Twitch.API_BASE); uriBuilder.setPath(urlPath); uriBuilder.setParameters(urlParameters); URI url = uriBuilder.build(); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); // add request header request.addHeader("User-Agent", USER_AGENT); request.addHeader("client_id", Twitch.CLIENT_ID); request.addHeader("Accept", Twitch.API_VERSION); HttpResponse response = client.execute(request); LogHelper.info("Sending 'GET' request to URL : " + url); LogHelper.info("Response Code : " + response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != 200) { ThreadManager.restartThreadTwitch(); return null; } BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); } return result.toString(); }
From source file:org.ireas.mediawiki.MediaWikiUtils.java
/** * Constructs an {@code URI} object from {@code scheme}, {@code host}, * {@code port} and {@code apiPath}. The constructed URI will have the * structure {@code "<scheme>://<host>:<port>/<apiPath>"}. * * @param scheme//w w w.ja v a2 s . c o m * the scheme of the URI, e. g. {@code "https"} * @param host * the host of the URI, e. g. {@code "example.org"} * @param port * the port of the URI, e. g. {@code 443}. The port must be * non-negative. * @param path * the path of the URI, e. g. {@code "/index.html"} * @return an {@code URI} constructed from the given parts * @throws MediaWikiException * if the given parts do not form a valid URI * @throws NullPointerException * if {@code scheme}, {@code host} or {@code path} is * {@code null} * @throws IllegalArgumentException * if {@code port} is negative */ public static URI buildUri(final String scheme, final String host, final int port, final String path) throws MediaWikiException { Preconditions.checkNotNull(scheme); Preconditions.checkNotNull(host); Preconditions.checkNotNull(path); Preconditions.checkArgument(port >= 0); URIBuilder uriBuilder = new URIBuilder(); uriBuilder.setScheme(scheme); uriBuilder.setHost(host); uriBuilder.setPort(port); uriBuilder.setPath(path); try { return uriBuilder.build(); } catch (URISyntaxException exception) { throw new MediaWikiException(exception); } }
From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java
public static String doGetTocken(ServerProfile sp, SSOServer srv, IProgressMonitor monitor) throws Exception { SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { // System.out.println("getAcceptedIssuers ============="); return null; }/*www . j av a2 s .c om*/ public void checkClientTrusted(X509Certificate[] certs, String authType) { // System.out.println("checkClientTrusted ============="); } public void checkServerTrusted(X509Certificate[] certs, String authType) { // System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf) .setRedirectStrategy(new DefaultRedirectStrategy() { @Override protected boolean isRedirectable(String arg0) { // TODO Auto-generated method stub return super.isRedirectable(arg0); } @Override public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { // TODO Auto-generated method stub return super.isRedirected(request, response, context); } }).setDefaultCookieStore(new BasicCookieStore()) .setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0") .build(); Executor exec = Executor.newInstance(httpclient); URIBuilder ub = new URIBuilder(sp.getUrl() + "index.html"); String fullURL = ub.build().toASCIIString(); Request req = HttpUtils.get(fullURL, sp); HttpHost proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL)); if (proxy != null) req.viaProxy(proxy); String tgtID = readData(exec, req, monitor); String action = getFormAction(tgtID); if (action != null) { action = action.replaceFirst("/", ""); int indx = action.indexOf(";jsession"); if (indx >= 0) action = action.substring(0, indx); } else action = "cas/login"; String url = srv.getUrl(); if (!url.endsWith("/")) url += "/"; ub = new URIBuilder(url + action); // fullURL = ub.build().toASCIIString(); req = HttpUtils.get(fullURL, sp); proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL)); if (proxy != null) req.viaProxy(proxy); tgtID = readData(exec, req, monitor); action = getFormAction(tgtID); action = action.replaceFirst("/", ""); ub = new URIBuilder(url + action); Map<String, String> map = getInputs(tgtID); Form form = Form.form(); for (String key : map.keySet()) { if (key.equals("btn-reset")) continue; else if (key.equals("username")) { form.add(key, srv.getUser()); continue; } else if (key.equals("password")) { form.add(key, Pass.getPass(srv.getPassword())); continue; } form.add(key, map.get(key)); } // req = HttpUtils.post(ub.build().toASCIIString(), form, sp); if (proxy != null) req.viaProxy(proxy); // Header header = null; readData(exec, req, monitor); // for (Header h : headers) { // for (HeaderElement he : h.getElements()) { // if (he.getName().equals("CASTGC")) { // header = new BasicHeader("Cookie", h.getValue()); // break; // } // } // } ub = new URIBuilder(url + action); url = sp.getUrl(); if (!url.endsWith("/")) url += "/"; ub.addParameter("service", url + "j_spring_security_check"); req = HttpUtils.get(ub.build().toASCIIString(), sp); if (proxy != null) req.viaProxy(proxy); // req.addHeader("Accept", // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, value"); req.addHeader("Referrer", sp.getUrl()); // req.addHeader(header); String html = readData(exec, req, monitor); Matcher matcher = ahrefPattern.matcher(html); while (matcher.find()) { Map<String, String> attributes = parseAttributes(matcher.group(1)); String v = attributes.get("href"); int ind = v.indexOf("ticket="); if (ind > 0) { return v.substring(ind + "ticket=".length()); } } return null; }
From source file:org.hl7.fhir.client.ResourceAddress.java
public static URI appendQueryStringToUri(URI uri, String parameterName, String parameterValue) { URI modifiedUri = null;/*from w w w . j a va 2 s. c o m*/ try { URIBuilder uriBuilder = new URIBuilder(uri); uriBuilder.setQuery(parameterName + "=" + parameterValue); modifiedUri = uriBuilder.build(); } catch (Exception e) { throw new EFhirClientException( "Unable to append query parameter '" + parameterName + "=" + parameterValue + " to URI " + uri, e); } return modifiedUri; }