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.google.api.services.samples.youtube.cmdline.data.Topics.java
/** * Retrieve Freebase topics that match a user-provided query term. Then * prompt the user to select a topic and return its topic ID. *//*from w w w . j av a2s . co m*/ private static String getTopicId() throws IOException { // The application will return an empty string if no matching topic ID // is found or no results are available. String topicsId = ""; // Prompt the user to enter a query term for finding Freebase topics. String topicQuery = getInputQuery("topics"); // The Freebase Java library does not provide search functionality, so // the application needs to call directly against the URL. This code // constructs the proper URL, then uses jackson classes to convert the // JSON response into a Java object. You can learn more about the // Freebase search calls at: http://wiki.freebase.com/wiki/ApiSearch. HttpClient httpclient = new DefaultHttpClient(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("query", topicQuery)); params.add(new BasicNameValuePair("limit", Long.toString(NUMBER_OF_TOPICS_RETURNED))); String serviceURL = "https://www.googleapis.com/freebase/v1/search"; String url = serviceURL + "?" + URLEncodedUtils.format(params, "UTF-8"); HttpResponse httpResponse = httpclient.execute(new HttpGet(url)); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { // Convert the JSON to an object. This code does not do an // exact map from JSON to POJO (Plain Old Java object), but // you could create additional classes and use them with the // mapper.readValue() function to get that exact mapping. ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.readValue(instream, JsonNode.class); // Confirm that the HTTP request was handled successfully by // checking the API response's HTTP response code. if (rootNode.get("status").asText().equals("200 OK")) { // In the API response, the "result" field contains the // list of needed results. ArrayNode arrayNodeResults = (ArrayNode) rootNode.get("result"); // Prompt the user to select a topic from the list of API // results. topicsId = getUserChoice(arrayNodeResults); } } finally { instream.close(); } } return topicsId; }
From source file:com.gargoylesoftware.htmlunit.html.HtmlForm.java
/** * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br> * * Gets the request for a submission of this form with the specified SubmittableElement. * @param submitElement the element that caused the submit to occur * @return the request//from w w w .j a va 2 s. co m */ public WebRequest getWebRequest(final SubmittableElement submitElement) { final HtmlPage htmlPage = (HtmlPage) getPage(); final List<NameValuePair> parameters = getParameterListForSubmit(submitElement); final HttpMethod method; final String methodAttribute = getMethodAttribute(); if ("post".equalsIgnoreCase(methodAttribute)) { method = HttpMethod.POST; } else { if (!"get".equalsIgnoreCase(methodAttribute) && StringUtils.isNotBlank(methodAttribute)) { notifyIncorrectness("Incorrect submit method >" + getMethodAttribute() + "<. Using >GET<."); } method = HttpMethod.GET; } final BrowserVersion browser = getPage().getWebClient().getBrowserVersion(); String actionUrl = getActionAttribute(); String anchor = null; String queryFromFields = ""; if (HttpMethod.GET == method) { if (actionUrl.contains("#")) { anchor = StringUtils.substringAfter(actionUrl, "#"); } final String enc = getPage().getPageEncoding(); queryFromFields = URLEncodedUtils.format(Arrays.asList(NameValuePair.toHttpClient(parameters)), enc); // action may already contain some query parameters: they have to be removed actionUrl = StringUtils.substringBefore(actionUrl, "#"); actionUrl = StringUtils.substringBefore(actionUrl, "?"); parameters.clear(); // parameters have been added to query } URL url; try { if (actionUrl.isEmpty()) { url = WebClient.expandUrl(htmlPage.getUrl(), actionUrl); } else { url = htmlPage.getFullyQualifiedUrl(actionUrl); } if (!queryFromFields.isEmpty()) { url = UrlUtils.getUrlWithNewQuery(url, queryFromFields); } if (HttpMethod.GET == method && browser.hasFeature(FORM_SUBMISSION_URL_WITHOUT_HASH) && WebClient.URL_ABOUT_BLANK != url) { url = UrlUtils.getUrlWithNewRef(url, null); } else if (HttpMethod.POST == method && browser.hasFeature(FORM_SUBMISSION_URL_WITHOUT_HASH) && WebClient.URL_ABOUT_BLANK != url && StringUtils.isEmpty(actionUrl)) { url = UrlUtils.getUrlWithNewRef(url, null); } else if (anchor != null && WebClient.URL_ABOUT_BLANK != url) { url = UrlUtils.getUrlWithNewRef(url, anchor); } } catch (final MalformedURLException e) { throw new IllegalArgumentException("Not a valid url: " + actionUrl); } final WebRequest request = new WebRequest(url, method); request.setRequestParameters(parameters); if (HttpMethod.POST == method) { request.setEncodingType(FormEncodingType.getInstance(getEnctypeAttribute())); } request.setCharset(getSubmitCharset()); request.setAdditionalHeader("Referer", htmlPage.getUrl().toExternalForm()); return request; }
From source file:org.opendatakit.common.security.spring.Oauth2ResourceFilter.java
private Map<String, Object> getJsonResponse(String url, String accessToken) { Map<String, Object> nullData = new HashMap<String, Object>(); // OK if we got here, we have a valid token. // Issue the request... URI nakedUri;//www .j av a 2 s . c o m try { nakedUri = new URI(url); } catch (URISyntaxException e2) { e2.printStackTrace(); logger.error(e2.toString()); return nullData; } List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("access_token", accessToken)); URI uri; try { uri = new URI(nakedUri.getScheme(), nakedUri.getUserInfo(), nakedUri.getHost(), nakedUri.getPort(), nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null); } catch (URISyntaxException e1) { e1.printStackTrace(); logger.error(e1.toString()); return nullData; } // DON'T NEED clientId on the toke request... // addCredentials(clientId, clientSecret, nakedUri.getHost()); // setup request interceptor to do preemptive auth // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS); HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS); // support redirecting to handle http: => https: transition HttpClientParams.setRedirecting(httpParams, true); // support authenticating HttpClientParams.setAuthenticating(httpParams, true); httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1); httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); // setup client HttpClient client = httpClientFactory.createHttpClient(httpParams); HttpGet httpget = new HttpGet(uri); logger.info(httpget.getURI().toString()); HttpResponse response = null; try { response = client.execute(httpget, new BasicHttpContext()); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.error("not 200: " + statusCode); return nullData; } else { HttpEntity entity = response.getEntity(); if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) { BufferedReader reader = null; InputStreamReader isr = null; try { reader = new BufferedReader(isr = new InputStreamReader(entity.getContent())); @SuppressWarnings("unchecked") Map<String, Object> userData = mapper.readValue(reader, Map.class); return userData; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // ignore } } if (isr != null) { try { isr.close(); } catch (IOException e) { // ignore } } } } else { logger.error("unexpected body"); return nullData; } } } catch (IOException e) { logger.error(e.toString()); return nullData; } catch (Exception e) { logger.error(e.toString()); return nullData; } }
From source file:groovyx.net.http.URIBuilder.java
protected URIBuilder setQueryNVP(List<NameValuePair> nvp) throws URISyntaxException { /* Passing the query string in the URI constructor will * double-escape query parameters and goober things up. So we have * to create a full path+query+fragment and use URI#resolve() to * create the new URI. *///from w w w.java 2 s.c om StringBuilder sb = new StringBuilder(); String path = base.getRawPath(); if (path != null) sb.append(path); sb.append('?'); sb.append(URLEncodedUtils.format(nvp, ENC)); String frag = base.getRawFragment(); if (frag != null) sb.append('#').append(frag); this.base = base.resolve(sb.toString()); return this; }
From source file:jp.gr.java_conf.petit_lycee.subsonico.MethodConstants.java
private String getRequestUrl(String reqMethod, List<BasicNameValuePair> param) { StringBuilder sb = new StringBuilder(); sb.append(top_url);/*from www .j a v a 2 s . co m*/ sb.append("rest/"); sb.append(reqMethod); sb.append(".view?"); sb.append("v="); sb.append(api_version); sb.append("&c="); sb.append(app_name); if (param != null) { sb.append("&"); sb.append(URLEncodedUtils.format(param, "UTF-8")); } return sb.toString(); }
From source file:org.jvoicexml.documentserver.schemestrategy.HttpSchemeStrategy.java
/** * Adds the parameters to the HTTP method. * /*from w ww. j a va 2s. c om*/ * @param parameters * parameters to add * @param uri * the given URI * @return URI with the given parameters * @throws URISyntaxException * error creating a URI * @throws SemanticError * error evaluating a parameter */ private URI addParameters(final Collection<KeyValuePair> parameters, final URI uri) throws URISyntaxException, SemanticError { if ((parameters == null) || parameters.isEmpty()) { return uri; } final ArrayList<NameValuePair> queryParameters = new ArrayList<NameValuePair>(); for (KeyValuePair current : parameters) { final Object value = current.getValue(); if (!(value instanceof File)) { final String name = current.getKey(); final NameValuePair pair = new BasicNameValuePair(name, value.toString()); queryParameters.add(pair); } } final Collection<NameValuePair> parameterList = URLEncodedUtils.parse(uri, encoding); queryParameters.addAll(parameterList); final String query = URLEncodedUtils.format(queryParameters, encoding); final URIBuilder builder = new URIBuilder(uri); builder.setQuery(query); return builder.build(); }
From source file:com.github.feribg.audiogetter.helpers.Utils.java
/** * Prepare soundcloud search URL//www . j a v a2s .c o m * @param query * @param offset * @return * @throws URISyntaxException */ public static URI getSoundCloudSearchURI(String query, Integer offset) throws URISyntaxException { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("client_id", Constants.Soundcloud.CLIENT_ID)); qparams.add(new BasicNameValuePair("offset", String.valueOf(offset))); qparams.add(new BasicNameValuePair("limit", String.valueOf(Constants.Soundcloud.PER_PAGE))); qparams.add(new BasicNameValuePair("q", query)); return URIUtils.createURI(Constants.Soundcloud.API_SCHEME, Constants.Soundcloud.API_HOST, -1, Constants.Soundcloud.API_SEARCH, URLEncodedUtils.format(qparams, "UTF-8"), null); }
From source file:eu.masconsult.bgbanking.banks.sgexpress.SGExpressClient.java
private String getUri(String xmlId, String userId, String sessionId) { String uri;/* www .j ava2s . c o m*/ uri = BASE_URL + "?" + URLEncodedUtils.format(Arrays.asList(new BasicNameValuePair(XML_ID, xmlId), new BasicNameValuePair(PARAM_USER_ID, userId), new BasicNameValuePair(PARAM_SESSION_ID, sessionId)), ENCODING); return uri; }
From source file:com.suning.mobile.ebuy.lottery.network.util.Caller.java
/** * //w ww. j a va2 s.c o m * @Description: * @Author 12050514 wangwt * @Date 2013-1-7 */ private NetworkBean get(List<NameValuePair> list, String action, boolean withCache) { NetworkBean subean = new NetworkBean(); list.add(new BasicNameValuePair("dcode", mApplication.getDeviceId())); list.add(new BasicNameValuePair("versionCode", String.valueOf(mApplication.getVersionCode()))); String tempUrl = getTempUrl(); String result = null; String url = tempUrl + action + "?" + URLEncodedUtils.format(list, LotteryApiConfig.ENCODE); if (mRequestCache != null && withCache) { result = mRequestCache.get(url); } if (result != null) { Log.d(TAG, "Caller.get [cached] " + url); subean = parseStringToSuBean(subean, result); } else { HttpGet request = new HttpGet(url); // request.addHeader("Accept-Encoding", "gzip"); LogUtil.d("http url", request.getURI().toString()); try { mClient.setCookieStore(SuningEBuyApplication.getInstance().getCookieStore()); HttpResponse response = mClient.execute(request); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); if (entity != null) { Header header = entity.getContentEncoding(); if (header != null) { String contentEncoding = header.getValue(); if (contentEncoding != null) { if (contentEncoding.contains("gzip")) { entity = new GzipDecompressingEntity(entity); } } } String charset = EntityUtils.getContentCharSet(entity) == null ? LotteryApiConfig.ENCODE : EntityUtils.getContentCharSet(entity); result = new String(EntityUtils.toByteArray(entity), charset); subean = parseStringToSuBean(subean, result); } } else { subean.setResult(2); subean.setMessage(mApplication.getResources().getString(R.string.cp_lottery_networkerror)); } } catch (ClientProtocolException e) { LogUtil.logException(e); subean.setResult(2); subean.setMessage(mApplication.getResources().getString(R.string.cp_lottery_networkerror)); } catch (IOException e) { LogUtil.logException(e); subean.setResult(2); subean.setMessage(mApplication.getResources().getString(R.string.cp_lottery_networkerror)); } catch (NullPointerException e) { LogUtil.logException(e); } finally { if (mRequestCache != null && withCache && subean.getResult() == 0) { // mRequestCache.put(url, result); } } } if (result != null) { LogUtil.d("http result", result); } return subean; }
From source file:com.teamlazerbeez.crm.sf.rest.HttpApiClient.java
@Nonnull private URI getUriForPath(String path, List<NameValuePair> params) throws IOException { try {//from ww w. j a v a 2 s.com return URIUtils.createURI("https", this.host, 443, path, URLEncodedUtils.format(params, "UTF-8"), null); } catch (URISyntaxException e) { throw new IOException("Couldn't create URI", e); } }