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:net.datacrow.onlinesearch.bol.BolClient.java
/** * Searches./*from w w w . j a v a 2 s .c o m*/ * * @param term The search term (required). * @param categoryID The category id and refinements, separated by spaces (optional). */ public String search(String term, String categoryID) throws IOException, URISyntaxException { List<NameValuePair> queryParams = new ArrayList<NameValuePair>(); queryParams.add(new BasicNameValuePair("term", term)); if (categoryID != null) queryParams.add(new BasicNameValuePair("categoryId", categoryID)); queryParams.add(new BasicNameValuePair("nrProducts", "10")); queryParams.add(new BasicNameValuePair("includeProducts", "TRUE")); queryParams.add(new BasicNameValuePair("includeCategories", "TRUE")); queryParams.add(new BasicNameValuePair("includeRefinements", "FALSE")); URIBuilder builder = new URIBuilder(); builder.setScheme("https"); builder.setHost("openapi.bol.com"); builder.setPath("/openapi/services/rest/catalog/v3/searchresults/"); builder.setQuery(URLEncodedUtils.format(queryParams, "UTF-8")); HttpGet httpGet = new HttpGet(builder.build()); HttpOAuthHelper au = new HttpOAuthHelper("application/xml"); au.handleRequest(httpGet, accessKeyId, secretAccessKey, null, queryParams); HttpResponse httpResponse = httpClient.execute(httpGet); String xml = getXML(httpResponse); httpClient.getConnectionManager().shutdown(); return xml; }
From source file:org.getwheat.harvest.library.RequestProcessor.java
private HttpUriRequest buildRequest(final Request<?> request, final UserCredentials credentials) throws URISyntaxException, UnsupportedEncodingException { final HttpUriRequest uriRequest = request.getHttpMethod().getRequest( URIUtils.createURI(VALUE_SCHEME, manager.getHostname(), -1, request.getResourcePath(), URLEncodedUtils.format(request.getParameters(), VALUE_UTF8), null).toString(), request.getRequestContent()); request.getTransformer().addContentTypeHeaders(uriRequest); addBasicAuthHeaders(uriRequest, credentials); return uriRequest; }
From source file:es.trigit.gitftask.Conexion.Http.java
/** * Performs http GET petition to server. * * @param url URL to perform GET petition. * @param parameters Parameters to include in petition. * * @return Response from the server.// w w w. j a v a 2 s . co m * @throws IOException If the <tt>parameters</tt> have errors, connection timed out, * socket timed out or other error related with the connection occurs. */ public static HttpResponse get(String url, ArrayList<NameValuePair> parameters) throws IOException { HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 10000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); int timeoutSocket = 10000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpClient httpclient = new DefaultHttpClient(httpParameters); if (parameters != null) { String paramString = URLEncodedUtils.format(parameters, "utf-8"); url += "?" + paramString; } HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); return response; }
From source file:de.huxhorn.whistler.services.JmpUrlShortener.java
public String shorten(String url) { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); // http://api.bit.ly/shorten?version=2.0.1&longUrl=http://cnn.com&login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07 qparams.add(new BasicNameValuePair("version", "2.0.1")); qparams.add(new BasicNameValuePair("longUrl", url)); if (login != null) { qparams.add(new BasicNameValuePair("login", login)); qparams.add(new BasicNameValuePair("apiKey", apiKey)); qparams.add(new BasicNameValuePair("history", "1")); }/*from w w w .j a v a 2 s. com*/ try { BasicHttpParams params = new BasicHttpParams(); /*params.setParameter(CookieSpecPNames.DATE_PATTERNS, Arrays.asList("EEE, dd-MMM-yyyy HH:mm:ss z", "EEE, dd MMM yyyy HH:mm:ss z")); params.setParameter( ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); BestMatchSpecFactory factory = new BestMatchSpecFactory(); CookieSpec cookiespec = factory.newInstance(params); */ DefaultHttpClient httpclient = new DefaultHttpClient(params); //httpclient.setCookieSpecs(cookiespec); //BestMatchSpecFactory factory = new BestMatchSpecFactory(); //CookieSpec cookiespec = factory.newInstance(params); //BasicHeader header = new BasicHeader("Set-Cookie", // "asid=011e7014f5e7718e02d893335aa5a16e; path=/; " + // "expires=Wed, 16-May-2018 17:13:32 GMT"); //CookieOrigin origin = new CookieOrigin("localhost", 80, "/", false); //List<Cookie> cookies = cookiespec.parse(header, origin); //System.out.println(cookies); // TODO: Cookie spec URI uri = URIUtils.createURI("http", "api.j.mp", -1, "/shorten", URLEncodedUtils.format(qparams, "UTF-8"), null); HttpGet httpget = new HttpGet(uri); if (logger.isDebugEnabled()) logger.debug("HttpGet.uri={}", httpget.getURI()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); JsonFactory f = new JsonFactory(); JsonParser jp = f.createJsonParser(instream); JmpShortenResponse responseObj = new JmpShortenResponse(); for (;;) { JsonToken token = jp.nextToken(); String fieldname = jp.getCurrentName(); if (logger.isDebugEnabled()) logger.debug("Token={}, currentName={}", token, fieldname); if (token == JsonToken.START_OBJECT) { continue; } if (token == JsonToken.END_OBJECT) { break; } if ("errorCode".equals(fieldname)) { token = jp.nextToken(); responseObj.setErrorCode(jp.getIntValue()); } else if ("errorMessage".equals(fieldname)) { token = jp.nextToken(); responseObj.setErrorMessage(jp.getText()); } else if ("statusCode".equals(fieldname)) { token = jp.nextToken(); responseObj.setStatusCode(jp.getText()); } else if ("results".equals(fieldname)) { // contains an object Map<String, ShortenedUrl> results = parseResults(jp); responseObj.setResults(results); } else { throw new IllegalStateException("Unrecognized field '" + fieldname + "'!"); } } Map<String, ShortenedUrl> results = responseObj.getResults(); if (results == null) { return null; } ShortenedUrl shortened = results.get(url); if (shortened == null) { return null; } if (logger.isDebugEnabled()) logger.debug("JmpShortenResponse: {}", responseObj); if ("OK".equals(responseObj.getStatusCode())) { return shortened.getShortUrl(); } // TODO: better error handling if (logger.isWarnEnabled()) logger.warn("JmpShortenResponse: {}", responseObj); } } catch (IOException ex) { if (logger.isWarnEnabled()) logger.warn("Exception!", ex); } catch (URISyntaxException ex) { if (logger.isWarnEnabled()) logger.warn("Exception!", ex); } // catch (MalformedCookieException ex) // { // if (logger.isWarnEnabled()) logger.warn("Exception!", ex); // } return null; }
From source file:model.web.ClientHttp.java
private String executeGet(List<NameValuePair> params) throws Exception { System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("GET parameters : " + params); HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url + "?" + URLEncodedUtils.format(params, "utf-8")); // add header get.setHeader("charset", "UTF-8"); get.setHeader("Content-Type", "application/json"); HttpResponse response = client.execute(get); System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line);/*from w w w .ja v a 2 s. c om*/ } System.out.println("result: " + result.toString()); return result.toString(); }
From source file:org.opennms.netmgt.bsm.vaadin.adminpage.BusinessServiceTreeTable.java
public BusinessServiceTreeTable(BusinessServiceManager businessServiceManager) { this.businessServiceManager = Objects.requireNonNull(businessServiceManager); setSizeFull();//from ww w . ja va2s .c o m setContainerDataSource(new BusinessServiceContainer()); // Add the "LINKS" columns addGeneratedColumn("links", new Table.ColumnGenerator() { private static final long serialVersionUID = 7113848887128656685L; @Override public Object generateCell(Table source, Object itemId, Object columnId) { final HorizontalLayout layout = new HorizontalLayout(); final BusinessServiceStateMachine stateMachine = businessServiceManager.getStateMachine(); final BusinessService businessService = getItem(itemId).getBean().getBusinessService(); final Status status = stateMachine.getOperationalStatus(businessService); if (status != null) { // Build the query string final List<BasicNameValuePair> urlParms = Lists.newArrayList( new BasicNameValuePair("focus-vertices", businessService.getId().toString()), new BasicNameValuePair("szl", "1"), new BasicNameValuePair("layout", "Hierarchy Layout"), new BasicNameValuePair("provider", "Business Services")); final String queryString = URLEncodedUtils.format(urlParms, Charset.forName("UTF-8")); // Generate the link final Link link = new Link("View in Topology UI", new ExternalResource(String.format("/opennms/topology?%s", queryString))); link.setIcon(FontAwesome.EXTERNAL_LINK_SQUARE); // This app is typically access in an iframe, so we open the URL in a new window/tab link.setTargetName("_blank"); layout.addComponent(link); layout.setComponentAlignment(link, Alignment.MIDDLE_CENTER); } else { Label label = new Label("N/A"); label.setDescription("Try reloading the daemon and refreshing the table."); label.setWidth(null); layout.addComponent(label); } return layout; } }); // add edit and delete buttons addGeneratedColumn("edit / delete", new Table.ColumnGenerator() { private static final long serialVersionUID = 7113848887128656685L; @Override public Object generateCell(Table source, Object itemId, Object columnId) { HorizontalLayout layout = new HorizontalLayout(); layout.setSpacing(true); Button editButton = new Button("Edit", FontAwesome.PENCIL_SQUARE_O); editButton.setId("editButton-" + getItem(itemId).getBean().getName()); editButton.addClickListener(UIHelper.getCurrent(TransactionAwareUI.class) .wrapInTransactionProxy((Button.ClickListener) event -> { final Long businessServiceId = getItem(itemId).getBean().getBusinessService().getId(); BusinessService businessService = businessServiceManager .getBusinessServiceById(businessServiceId); final BusinessServiceEditWindow window = new BusinessServiceEditWindow(businessService, businessServiceManager); window.addCloseListener(e -> refresh()); getUI().addWindow(window); })); layout.addComponent(editButton); Button deleteButton = new Button("Delete", FontAwesome.TRASH_O); deleteButton.setId("deleteButton-" + getItem(itemId).getBean().getName()); deleteButton.addClickListener((Button.ClickListener) event -> { final Long businessServiceId = getItem(itemId).getBean().getBusinessService().getId(); BusinessService businessService = businessServiceManager .getBusinessServiceById(businessServiceId); if (businessService.getParentServices().isEmpty() && businessService.getChildEdges().isEmpty()) { UIHelper.getCurrent(TransactionAwareUI.class).runInTransaction(() -> { businessServiceManager.getBusinessServiceById(businessServiceId).delete(); refresh(); }); } else { new org.opennms.netmgt.vaadin.core.ConfirmationDialog() .withOkAction((org.opennms.netmgt.vaadin.core.ConfirmationDialog.Action) UIHelper .getCurrent(TransactionAwareUI.class).wrapInTransactionProxy( new org.opennms.netmgt.vaadin.core.ConfirmationDialog.Action() { @Override public void execute( org.opennms.netmgt.vaadin.core.ConfirmationDialog window) { businessServiceManager .getBusinessServiceById(businessServiceId).delete(); refresh(); } })) .withOkLabel("Delete anyway").withCancelLabel("Cancel").withCaption("Warning") .withDescription( "This entry is referencing or is referenced by other Business Services! Do you really want to delete this entry?") .open(); } }); layout.addComponent(deleteButton); return layout; } }); setColumnExpandRatio("name", 5); setColumnExpandRatio("links", 1); setColumnExpandRatio("edit / delete", 1); }
From source file:com.cloudapp.rest.CloudApi.java
/** * Create a bookmark.//from w ww .j av a2 s . com * * @param name * The name of the bookmark. * @param url * The URL of the bookmark * @return a JSONObject with the info that was return by the CloudApp servers. * @throws CloudApiException */ public JSONObject createBookmark(String name, String url) throws CloudApiException { HttpPost request = null; try { // Apparently we have to post a JSONObject .. JSONObject item = new JSONObject(); item.put("name", name); item.put("redirect_url", url); JSONObject bodyObj = new JSONObject(); bodyObj.put("item", item); String body = bodyObj.toString(2); System.out.println(bodyObj.toString(2)); // Prepare the parameters List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("item[redirect_url]", url)); nvps.add(new BasicNameValuePair("item[name]", name)); // Prepare the request. URI uri = URIUtils.createURI("http", "my.cl.ly", -1, "/items", URLEncodedUtils.format(nvps, "UTF-8"), null); request = new HttpPost(uri); request.setHeader("Accept", "application/json"); // Fire it HttpResponse response = client.execute(request); int status = response.getStatusLine().getStatusCode(); body = EntityUtils.toString(response.getEntity()); // Only 200 means success. if (status == 200) { return new JSONObject(body); } throw new CloudApiException(status, body, null); } catch (JSONException e) { LOGGER.error("Error when trying to convert the return output to JSON.", e); throw new CloudApiException(500, e.getMessage(), e); } catch (IOException e) { LOGGER.error("Unable to create bookmark.", e); throw new CloudApiException(500, e.getMessage(), e); } catch (URISyntaxException e) { LOGGER.error("Unable to create bookmark.", e); throw new CloudApiException(500, e.getMessage(), e); } finally { if (request != null) { request.abort(); } } }
From source file:org.hawk.service.emf.impl.HawkResourceFactoryImpl.java
/** * From a {@link HawkModelDescriptor}, this method produces a string * representation of an URI that can be used to load a model indexed by Hawk * without a <code>.hawkmodel</code> file. If * <code>removeDefaultValues</code> is true, the fields with default values * will not be put in the URL. This may not work correctly if the server and * the client have different default values, but it produces much shorter * URLs most of the time.//from w ww. j a v a 2s . c o m */ public static String generateHawkURL(HawkModelDescriptor d, boolean removeDefaultValues) throws UnsupportedEncodingException { final List<NameValuePair> params = new ArrayList<>(); addParameter(params, URLPARAM_INSTANCE, d.getHawkInstance(), HawkModelDescriptor.DEFAULT_INSTANCE, removeDefaultValues); addParameter(params, URLPARAM_FILE_PATTERNS, join(d.getHawkFilePatterns(), ","), HawkModelDescriptor.DEFAULT_FILES, removeDefaultValues); addParameter(params, URLPARAM_THRIFT_PROTOCOL, d.getThriftProtocol().name().toUpperCase(), HawkModelDescriptor.DEFAULT_TPROTOCOL.name().toUpperCase(), removeDefaultValues); addParameter(params, URLPARAM_REPOSITORY, d.getHawkRepository(), HawkModelDescriptor.DEFAULT_REPOSITORY, removeDefaultValues); addParameter(params, URLPARAM_LOADING_MODE, d.getLoadingMode().name().toUpperCase(), HawkModelDescriptor.DEFAULT_LOADING_MODE.name().toUpperCase(), removeDefaultValues); addParameter(params, URLPARAM_QUERY_LANGUAGE, d.getHawkQueryLanguage(), HawkModelDescriptor.DEFAULT_QUERY_LANGUAGE, removeDefaultValues); addParameter(params, URLPARAM_QUERY, d.getHawkQuery(), HawkModelDescriptor.DEFAULT_QUERY, removeDefaultValues); addParameter(params, URLPARAM_DEFAULT_NAMESPACES, d.getDefaultNamespaces(), HawkModelDescriptor.DEFAULT_DEFAULT_NAMESPACES, removeDefaultValues); addParameter(params, URLPARAM_SPLIT, d.isSplit() + "", HawkModelDescriptor.DEFAULT_IS_SPLIT + "", removeDefaultValues); addParameter(params, URLPARAM_SUBSCRIBE, d.isSubscribed() + "", HawkModelDescriptor.DEFAULT_IS_SUBSCRIBED + "", removeDefaultValues); if (d.isSubscribed()) { addParameter(params, URLPARAM_DURABILITY, d.getSubscriptionDurability().name().toUpperCase(), HawkModelDescriptor.DEFAULT_DURABILITY.name().toUpperCase(), removeDefaultValues); addParameter(params, URLPARAM_CLIENTID, d.getSubscriptionClientID(), null, removeDefaultValues); } final StringBuffer url = new StringBuffer("hawk+"); url.append(d.getHawkURL()); url.append("?"); url.append(URLEncodedUtils.format(params, Charset.forName("UTF-8"))); return url.toString(); }
From source file:org.ambraproject.wombat.freemarker.ReplaceParametersDirective.java
public void execute(Environment environment, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { if (!params.keySet().equals(EXPECTED_KEYS)) { throw new TemplateException("ReplaceParametersDirective requires keys: " + EXPECTED_KEYS, environment); }/*from w ww.j a v a2s. com*/ // I have no idea why freemarker feels the need to invent their own collection classes... SimpleHash parameterMap = (SimpleHash) params.get(PARAMETER_MAP_KEY); Multimap<String, TemplateModel> replacements = TemplateModelUtil .getAsMultimap((TemplateModel) params.get(REPLACEMENTS_KEY)); Multimap<String, String> outputParams = replaceParameters(parameterMap, replacements); List<NameValuePair> paramList = new ArrayList<>(outputParams.size()); for (String key : outputParams.keySet()) { for (String value : outputParams.get(key)) { paramList.add(new BasicNameValuePair(key, value)); } } environment.getOut().write(URLEncodedUtils.format(paramList, "UTF-8")); }