List of usage examples for org.apache.http.client.utils URLEncodedUtils format
public static String format(final Iterable<? extends NameValuePair> parameters, final Charset charset)
From source file:com.autonomy.aci.client.transport.impl.AciHttpClientImpl.java
/** * Converts a list of {@code AciParameter} objects into an array of {@code NameValuePair} objects suitable for use * in both POST and GET methods./*from w w w. j a v a 2s. co m*/ * @param parameters The set of parameters to convert. * @param charsetName The name of the charset to use when encoding the parameters * @return an <tt>String</tt> representing the query string portion of a URI */ private String convertParameters(final Set<? extends ActionParameter<?>> parameters, final String charsetName) { LOGGER.trace("convertParameters() called..."); // Just incase, remove the allowed null entry... parameters.remove(null); final List<NameValuePair> pairs = new ArrayList<>(parameters.size()); LOGGER.debug("Converting {} parameters...", parameters.size()); NameValuePair actionPair = null; for (final ActionParameter<?> parameter : parameters) { final Object value = parameter.getValue(); if (value instanceof String) { final String stringValue = (String) value; if (AciConstants.PARAM_ACTION.equalsIgnoreCase(parameter.getName())) { actionPair = new BasicNameValuePair(parameter.getName(), stringValue); } else { pairs.add(new BasicNameValuePair(parameter.getName(), stringValue)); } } } // Ensure that the action=XXX parameter is the first thing in the list... Validate.isTrue(actionPair != null, "No action parameter found in parameter set, please set one before trying to execute an ACI request."); pairs.add(0, actionPair); // Convert to a string and return... return URLEncodedUtils.format(pairs, charsetName); }
From source file:org.extensiblecatalog.ncip.v2.symphony.SymphonyHttpService.java
private <T extends SymphonyResponse<?>> T executeRequest(String pathInfo, List<NameValuePair> params, Class<T> responseClass) throws HttpException { String queryString = URLEncodedUtils.format(params, "utf-8"); URI uri = URI.create(symphonyBaseURL + pathInfo + "?" + queryString); logger.info("Executing query on " + uri.toString()); HttpGet get = new HttpGet(uri); HttpEntity entity = null;//from www.j a va 2 s.co m try { HttpResponse resp = client.execute(get); entity = resp.getEntity(); return mapper.readStream(entity.getContent(), responseClass); } catch (UnsupportedEncodingException e) { throw new HttpException(e); } catch (ClientProtocolException e) { throw new HttpException(e); } catch (IOException e) { throw new HttpException(e); } finally { if (entity != null) { try { entity.getContent().close(); } catch (IOException iox) { // ignore } } } }
From source file:com.tri_voltage.md.io.YoutubeVideoParser.java
private static URI getUri(String path, List<NameValuePair> qparams) throws URISyntaxException { URI uri = URIUtils.createURI(scheme, host, -1, "/" + path, URLEncodedUtils.format(qparams, DEFAULT_ENCODING), null); return uri;//from w ww .j a v a 2 s . c o m }
From source file:de.geeksfactory.opacclient.apis.TouchPoint.java
@Override public SearchRequestResult search(List<SearchQuery> query) throws IOException, OpacErrorException, JSONException { List<NameValuePair> params = new ArrayList<>(); int index = 0; start();/*from w ww . ja va 2 s . co m*/ params.add(new BasicNameValuePair("methodToCall", "submitButtonCall")); params.add(new BasicNameValuePair("CSId", CSId)); params.add(new BasicNameValuePair("methodToCallParameter", "submitSearch")); params.add(new BasicNameValuePair("refine", "false")); for (SearchQuery entry : query) { if (entry.getValue().equals("")) { continue; } if (entry.getSearchField() instanceof DropdownSearchField) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } else { if (index != 0) { params.add(new BasicNameValuePair("combinationOperator[" + index + "]", "AND")); } params.add(new BasicNameValuePair("searchCategories[" + index + "]", entry.getKey())); params.add(new BasicNameValuePair("searchString[" + index + "]", entry.getValue())); index++; } } if (index == 0) { throw new OpacErrorException(stringProvider.getString(StringProvider.NO_CRITERIA_INPUT)); } if (index > 4) { throw new OpacErrorException( stringProvider.getQuantityString(StringProvider.LIMITED_NUM_OF_CRITERIA, 4, 4)); } params.add(new BasicNameValuePair("submitButtonCall_submitSearch", "Suchen")); params.add(new BasicNameValuePair("numberOfHits", "10")); String html = httpGet(opac_url + "/search.do?" + URLEncodedUtils.format(params, "UTF-8"), ENCODING); return parse_search(html, 1); }
From source file:org.apache.gobblin.example.wikipedia.WikipediaExtractor.java
public static URI createRequestURI(String rootUrl, Map<String, String> query) throws MalformedURLException, URISyntaxException { List<NameValuePair> queryTokens = Lists.newArrayList(); for (Map.Entry<String, String> entry : query.entrySet()) { queryTokens.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); }//w ww .java 2 s. c o m String encodedQuery = URLEncodedUtils.format(queryTokens, Charsets.UTF_8); URI actualURL = new URIBuilder(rootUrl).setQuery(encodedQuery).build(); return actualURL; }
From source file:org.elasticsearch.xpack.watcher.common.http.HttpClient.java
private URI createURI(HttpRequest request) { // this could be really simple, as the apache http client has a UriBuilder class, however this class is always doing // url path escaping, and we have done this already, so this would result in double escaping try {//from w w w .ja va 2s. com List<NameValuePair> qparams = new ArrayList<>(request.params.size()); request.params.forEach((k, v) -> qparams.add(new BasicNameValuePair(k, v))); String format = URLEncodedUtils.format(qparams, "UTF-8"); URI uri = URIUtils.createURI(request.scheme.scheme(), request.host, request.port, request.path, Strings.isNullOrEmpty(format) ? null : format, null); return uri; } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
From source file:com.archivas.clienttools.arcutils.impl.adapter.HCAPAdapter.java
public void delete(final String path, boolean isDirectory, DeleteJob.Operation operation, String reason, boolean isCustomMetadata) throws StorageAdapterException { HttpHost httpHost = new HttpHost(getHost(), ((HCAPProfile) getProfile()).getPort(), getProfile().getProtocol()); String resolvedPath = path;/*w ww .j ava 2 s . c o m*/ if (!resolvedPath.startsWith(HttpGatewayConstants.METADATA_MOUNT_URL_DIR)) { resolvedPath = getProfile().resolvePath(resolvedPath); } // Handle Delete Parameters List<NameValuePair> deleteOperations; if (isDirectory) { // Directories don't need any special flags deleteOperations = null; } else if (operation == DeleteJob.Operation.PRIVILEGED_DELETE) { if (reason == null || reason.equals("")) { throw new StorageAdapterLiteralException("When doing a privileged delete a reason is required."); } deleteOperations = new ArrayList<NameValuePair>(); deleteOperations.add(new BasicNameValuePair(HttpGatewayConstants.PARAM_PRIVILEGED, "true")); deleteOperations.add(new BasicNameValuePair(HttpGatewayConstants.PARAM_REASON, reason)); } else { deleteOperations = handleDeleteOperation(operation, reason); } if (isCustomMetadata) { if (deleteOperations == null) { deleteOperations = new ArrayList<NameValuePair>(); } deleteOperations.add(new BasicNameValuePair(HttpGatewayConstants.MD_TYPE, "custom-metadata")); } String queryString = null; if (deleteOperations != null && deleteOperations.size() > 0) { queryString = URLEncodedUtils.format(deleteOperations, "UTF-8"); } // Constructing a uri handles the filename encoding for us here URI uri; try { uri = URIUtils.createURI(getProfile().getProtocol(), getHost(), -1, resolvedPath, queryString, null); } catch (URISyntaxException e) { LOG.log(Level.INFO, "Unexpected error generating put URI for : " + resolvedPath); throw new StorageAdapterLiteralException("Error during delete", e); } HttpDelete request = new HttpDelete(uri); // Eventually we will just return this cookie which will be passed back to the caller. HcapAdapterCookie cookie = new HcapAdapterCookie(request, httpHost); synchronized (savingCookieLock) { if (savedCookie != null) { throw new RuntimeException( "This adapter already has a current connection to host -- cannot create two at once."); } savedCookie = cookie; } try { executeMethod(cookie); this.handleHttpResponse(cookie.getResponse(), "deleting", path); } catch (IOException e) { handleIOExceptionFromRequest(e, "deleting", path); } finally { close(); } }
From source file:io.gs2.inbox.Gs2InboxClient.java
/** * ????????<br>//from w w w. j a v a 2 s . c o m * <br> * - : ?? * 10<br> * <br> * * @param request */ public void deleteMessages(DeleteMessagesRequest request) { String url = Gs2Constant.ENDPOINT_HOST + "/inbox/" + (request.getInboxName() == null || request.getInboxName().equals("") ? "null" : request.getInboxName()) + "/message/multiple"; List<NameValuePair> queryString = new ArrayList<>(); if (request.getMessageIds() != null) queryString.add(new BasicNameValuePair("messageIds", toString(request.getMessageIds()))); if (queryString.size() > 0) { url += "?" + URLEncodedUtils.format(queryString, "UTF-8"); } HttpDelete delete = createHttpDelete(url, credential, ENDPOINT, DeleteMessagesRequest.Constant.MODULE, DeleteMessagesRequest.Constant.FUNCTION); if (request.getRequestId() != null) { delete.setHeader("X-GS2-REQUEST-ID", request.getRequestId()); } doRequest(delete, null); }
From source file:org.dvbviewer.controller.ui.fragments.TimerDetails.java
@Override public void onClick(View v) { DateDialogFragment f;//from w ww.ja v a2 s .c o m switch (v.getId()) { case R.id.dateField: f = DateDialogFragment.newInstance(getActivity(), (OnDateSetListener) TimerDetails.this, dateField.getDate()); f.show(getSherlockActivity().getSupportFragmentManager(), "datepicker"); break; case R.id.startField: f = DateDialogFragment.newInstance(getActivity(), startTimeSetListener, startField.getDate()); f.show(getSherlockActivity().getSupportFragmentManager(), "startTimePicker"); break; case R.id.stopField: f = DateDialogFragment.newInstance(getActivity(), stopTimeSetListener, stopField.getDate()); f.show(getSherlockActivity().getSupportFragmentManager(), "stopTimePicker"); break; case R.id.buttonCancel: if (mOntimeredEditedListener != null) { mOntimeredEditedListener.timerEdited(true); } dismiss(); break; case R.id.buttonOk: String url = timer.getId() <= 0l ? ServerConsts.URL_TIMER_CREATE : ServerConsts.URL_TIMER_EDIT; String title = titleField.getText().toString(); String days = String.valueOf(DateUtils.getDaysSinceDelphiNull(dateField.getDate())); String start = String.valueOf(DateUtils.getMinutesOfDay(startField.getDate())); String stop = String.valueOf(DateUtils.getMinutesOfDay(stopField.getDate())); String endAction = String.valueOf(postRecordSpinner.getSelectedItemPosition()); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ch", String.valueOf(timer.getChannelId()))); params.add(new BasicNameValuePair("dor", days)); params.add(new BasicNameValuePair("encoding", "255")); params.add(new BasicNameValuePair("enable", "1")); params.add(new BasicNameValuePair("start", start)); params.add(new BasicNameValuePair("stop", stop)); params.add(new BasicNameValuePair("title", title)); params.add(new BasicNameValuePair("endact", endAction)); if (timer.getId() > 0) { params.add(new BasicNameValuePair("id", String.valueOf(timer.getId()))); } String query = URLEncodedUtils.format(params, "utf-8"); String request = url + query; RecordingServiceGet rsGet = new RecordingServiceGet(request); Thread executionThread = new Thread(rsGet); executionThread.start(); if (mOntimeredEditedListener != null) { mOntimeredEditedListener.timerEdited(true); } if (getDialog() != null && getDialog().isShowing()) { dismiss(); } break; default: break; } }
From source file:com.mnxfst.testing.activities.http.AbstractHTTPRequestActivity.java
/** * @see com.mnxfst.testing.activities.TSPlanActivity#initialize(com.mnxfst.testing.plan.config.TSPlanConfigOption) */// ww w . ja v a2 s . co m public void initialize(TSPlanConfigOption cfg) throws TSPlanActivityExecutionException { if (cfg == null) throw new TSPlanActivityExecutionException("Failed to initialize activity '" + this.getClass().getName() + "' due to missing configuration options"); ///////////////////////////////////////////////////////////////////////////////////////// // fetch scheme, host, port and path this.scheme = (String) cfg.getOption(CFG_OPT_SCHEME); if (this.scheme == null || this.scheme.isEmpty()) throw new TSPlanActivityExecutionException( "Required config option '" + CFG_OPT_SCHEME + "' missing for activity '" + getName() + "'"); this.host = (String) cfg.getOption(CFG_OPT_HOST); if (this.host == null || this.host.isEmpty()) throw new TSPlanActivityExecutionException( "Requied config option '" + CFG_OPT_HOST + "' missing for activity '" + getName() + "'"); String portStr = (String) cfg.getOption(CFG_OPT_PORT); if (portStr != null && !portStr.isEmpty()) { try { this.port = Integer.parseInt(portStr.trim()); } catch (NumberFormatException e) { throw new TSPlanActivityExecutionException( "Failed to parse expected numerical value for config option '" + CFG_OPT_PORT + "' for activity '" + getName() + "'"); } } // fetch username and password this.basicAuthUsername = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_USERNAME); this.basicAuthPassword = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_PASSWORD); this.basicAuthHostScope = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_HOST_SCOPE); String authPortScopeStr = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_PORT_SCOPE); if (authPortScopeStr != null && !authPortScopeStr.trim().isEmpty()) { try { this.basicAuthPortScope = Integer.parseInt(authPortScopeStr.trim()); } catch (NumberFormatException e) { throw new TSPlanActivityExecutionException( "Failed to parse expected numerical value for config option '" + CFG_OPT_BASIC_AUTH_PORT_SCOPE + "' for activity '" + getName() + "'"); } } if (this.port <= 0) this.port = 80; this.path = (String) cfg.getOption(CFG_OPT_PATH); if (this.path == null || this.path.isEmpty()) this.path = "/"; String maxConnStr = (String) cfg.getOption(CFG_OPT_MAX_CONNECTIONS); if (maxConnStr != null && !maxConnStr.isEmpty()) { try { this.maxConnections = Integer.parseInt(maxConnStr); } catch (NumberFormatException e) { throw new TSPlanActivityExecutionException( "Failed to parse expected numerical value for config option '" + CFG_OPT_MAX_CONNECTIONS + "' for activity '" + getName() + "'"); } } // initialize http host and context this.httpHost = new HttpHost(this.host, this.port); // URI builder try { // query parameters List<NameValuePair> qParams = new ArrayList<NameValuePair>(); for (String key : cfg.getOptions().keySet()) { if (key.startsWith(REQUEST_PARAM_OPTION_PREFIX)) { String value = (String) cfg.getOption(key); String requestParameterName = key.substring(REQUEST_PARAM_OPTION_PREFIX.length(), key.length()); qParams.add(new BasicNameValuePair(requestParameterName, value)); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", requestParameter=" + requestParameterName + ", value=" + value + "]"); } } this.destinationURI = URIUtils.createURI(this.scheme, this.host, this.port, this.path, URLEncodedUtils.format(qParams, this.contentChartset), null); // TODO handle post values } catch (URISyntaxException e) { throw new TSPlanActivityExecutionException("Failed to initialize uri for [scheme=" + this.scheme + ", host=" + this.host + ", port=" + this.port + ", path=" + this.path + "]"); } httpRequestContext.setAttribute(ExecutionContext.HTTP_CONNECTION, clientConnection); httpRequestContext.setAttribute(ExecutionContext.HTTP_TARGET_HOST, httpHost); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", maxConnections=" + maxConnections + ", scheme=" + scheme + ", host=" + host + ", port=" + port + ", path=" + path + "]"); ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// // protocol settings this.userAgent = (String) cfg.getOption(CFG_OPT_USER_AGENT); if (this.userAgent == null || this.userAgent.isEmpty()) this.userAgent = "ptest-server"; String protocolVersion = (String) cfg.getOption(CFG_OPT_HTTP_PROTOCOL_VERSION); if (protocolVersion != null && !protocolVersion.isEmpty()) { if (protocolVersion.equalsIgnoreCase("0.9")) this.httpVersion = HttpVersion.HTTP_0_9; else if (protocolVersion.equalsIgnoreCase("1.0")) this.httpVersion = HttpVersion.HTTP_1_0; else if (protocolVersion.equalsIgnoreCase("1.1")) this.httpVersion = HttpVersion.HTTP_1_1; else throw new TSPlanActivityExecutionException("Failed to parse http protocol version '" + protocolVersion + "'. Valid value: 0.9, 1.0 and 1.1"); } this.contentChartset = (String) cfg.getOption(CFG_OPT_CONTENT_CHARSET); if (this.contentChartset == null || this.contentChartset.isEmpty()) this.contentChartset = "UTF-8"; String expectContStr = (String) cfg.getOption(CFG_OPT_EXPECT_CONTINUE); if (expectContStr != null && !expectContStr.isEmpty()) { this.expectContinue = Boolean.parseBoolean(expectContStr.trim()); } HttpProtocolParams.setUserAgent(httpParameters, userAgent); HttpProtocolParams.setVersion(httpParameters, httpVersion); HttpProtocolParams.setContentCharset(httpParameters, contentChartset); HttpProtocolParams.setUseExpectContinue(httpParameters, expectContinue); String httpProcStr = (String) cfg.getOption(CFG_OPT_HTTP_REQUEST_PROCESSORS); if (httpProcStr != null && !httpProcStr.isEmpty()) { List<HttpRequestInterceptor> interceptors = new ArrayList<HttpRequestInterceptor>(); String[] procClasses = httpProcStr.split(","); if (procClasses != null && procClasses.length > 0) { for (int i = 0; i < procClasses.length; i++) { try { Class<?> clazz = Class.forName(procClasses[i]); interceptors.add((HttpRequestInterceptor) clazz.newInstance()); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", httpRequestInterceptor=" + procClasses[i] + "]"); } catch (Exception e) { throw new TSPlanActivityExecutionException("Failed to instantiate http interceptor '" + procClasses[i] + "' for activity '" + getName() + "'. Error: " + e.getMessage()); } } } this.httpRequestResponseProcessor = new ImmutableHttpProcessor( (HttpRequestInterceptor[]) interceptors.toArray(EMPTY_HTTP_REQUEST_INTERCEPTOR_ARRAY)); this.hasRequestResponseProcessors = true; } this.method = (String) cfg.getOption(CFG_OPT_METHOD); if (method == null || method.isEmpty()) this.method = "GET"; if (!method.equalsIgnoreCase("get") && !method.equalsIgnoreCase("post")) throw new TSPlanActivityExecutionException( "Invalid method '" + method + "' found for activity '" + getName() + "'"); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", method=" + method + ", user-agent=" + userAgent + ", httpVersion=" + httpVersion + ", contentCharset=" + contentChartset + ", expectContinue=" + expectContinue + "]"); ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// // fetch proxy settings this.proxyUrl = (String) cfg.getOption(CFG_OPT_PROXY_URL); String proxyPortStr = (String) cfg.getOption(CFG_OPT_PROXY_PORT); if (proxyPortStr != null && !proxyPortStr.isEmpty()) { try { this.proxyPort = Integer.parseInt(proxyPortStr.trim()); } catch (NumberFormatException e) { throw new TSPlanActivityExecutionException( "Failed to parse expected numerical value for config option '" + CFG_OPT_PROXY_PORT + "' for activity '" + getName() + "'"); } } this.proxyUser = (String) cfg.getOption(CFG_OPT_PROXY_USER); this.proxyPassword = (String) cfg.getOption(CFG_OPT_PROXY_PASSWORD); if (proxyUrl != null && !proxyUrl.isEmpty()) { if (proxyPort > 0) this.proxyHost = new HttpHost(proxyUrl, proxyPort); else this.proxyHost = new HttpHost(proxyUrl); } if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", proxyUrl=" + proxyUrl + ", proxyPort=" + proxyPort + ", proxyUser=" + proxyUser + "]"); ///////////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////////// // // fetch request parameters // // // unfortunately we must step through the whole set of keys ... // for(String key : cfg.getOptions().keySet()) { // if(key.startsWith(REQUEST_PARAM_OPTION_PREFIX)) { // String value = (String)cfg.getOption(key); // String requestParameterName = key.substring(REQUEST_PARAM_OPTION_PREFIX.length(), key.length()); // httpParameters.setParameter(requestParameterName, value); // if(logger.isDebugEnabled()) // logger.debug("activity[name="+getName()+", id="+getId()+", requestParameter="+requestParameterName+", value="+value+"]"); // } // } // // ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// // configure scheme registry and initialize http client SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", registeredSchemes={http, https}]"); ThreadSafeClientConnManager threadSafeClientConnectionManager = new ThreadSafeClientConnManager( schemeRegistry); threadSafeClientConnectionManager.setMaxTotal(maxConnections); threadSafeClientConnectionManager.setDefaultMaxPerRoute(maxConnections); this.httpClient = new DefaultHttpClient(threadSafeClientConnectionManager); if (this.basicAuthUsername != null && !this.basicAuthUsername.trim().isEmpty() && this.basicAuthPassword != null && !this.basicAuthPassword.trim().isEmpty()) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(this.basicAuthUsername, this.basicAuthPassword); AuthScope authScope = null; if (basicAuthHostScope != null && !basicAuthHostScope.isEmpty() && basicAuthPortScope > 0) { authScope = new AuthScope(basicAuthHostScope, basicAuthPortScope); } else { authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); } this.httpClient.getCredentialsProvider().setCredentials(authScope, creds); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", credentials=(" + creds.getUserName() + ", " + creds.getPassword() + "), authScope=(" + authScope.getHost() + ":" + authScope.getPort() + ")]"); } if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", threadSafeClientConnectionManager=initialized]"); }