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:io.gs2.realtime.Gs2RealtimeClient.java
/** * ?????<br>// w w w .j a va 2 s . c om * <br> * * @param request * @return ? */ public DescribeGatheringResult describeGathering(DescribeGatheringRequest request) { String url = Gs2Constant.ENDPOINT_HOST + "/gatheringPool/" + (request.getGatheringPoolName() == null || request.getGatheringPoolName().equals("") ? "null" : request.getGatheringPoolName()) + "/gathering"; List<NameValuePair> queryString = new ArrayList<>(); if (request.getPageToken() != null) queryString.add(new BasicNameValuePair("pageToken", String.valueOf(request.getPageToken()))); if (request.getLimit() != null) queryString.add(new BasicNameValuePair("limit", String.valueOf(request.getLimit()))); if (queryString.size() > 0) { url += "?" + URLEncodedUtils.format(queryString, "UTF-8"); } HttpGet get = createHttpGet(url, credential, ENDPOINT, DescribeGatheringRequest.Constant.MODULE, DescribeGatheringRequest.Constant.FUNCTION); if (request.getRequestId() != null) { get.setHeader("X-GS2-REQUEST-ID", request.getRequestId()); } return doRequest(get, DescribeGatheringResult.class); }
From source file:org.craftercms.social.util.UGCHttpClient.java
public HttpResponse getThread(String ticket, String ugcId) throws Exception { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("ticket", ticket)); URI uri = URIUtils.createURI(scheme, host, port, appPath + "/api/2/ugc/thread/" + ugcId + ".json", URLEncodedUtils.format(qparams, HTTP.UTF_8), null); HttpGet httpget = new HttpGet(uri); HttpClient httpclient = new DefaultHttpClient(); return httpclient.execute(httpget); }
From source file:retrovolley.request.RequestBuilder.java
/** * Prepare the GET request URL and append required parameters * * @param url The url string value/*from w w w.j a va 2 s .c om*/ * @param params The parameters map * @return A new url with appended parameters */ public static String buildGETUrl(String url, List<Pair<String, String>> params) { final StringBuilder urlBuilder = new StringBuilder(url); /* Simple null check */ if (params != null && !params.isEmpty()) { /* Add question mark is not present */ if (!url.endsWith("?")) { urlBuilder.append("?"); } /* Create GET parameters */ List<NameValuePair> getParams = new LinkedList<NameValuePair>(); for (Pair<String, String> param : params) { getParams.add(new BasicNameValuePair(param.first, param.second)); } urlBuilder.append(URLEncodedUtils.format(getParams, "utf-8")); } return urlBuilder.toString(); }
From source file:cn.kuwo.sing.phone4tv.commons.http.RequestParams.java
protected String getParamString(String encoding) { return URLEncodedUtils.format(getParamsList(), encoding); }
From source file:com.cloudapp.rest.CloudApi.java
/** * /*from w w w . j a v a 2 s . c om*/ * {@inheritDoc} * * @see com.cloudapp.rest.CloudApi#getItems() */ public JSONArray getItems(int page, int itemsPerPage, String type, boolean showDeleted) throws CloudApiException { HttpGet request = null; try { // Sanitize the parameters if (page < 1) { page = 1; } if (itemsPerPage < 1) { itemsPerPage = 1; } // Prepare the list of parameters. List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("page", "" + page)); nvps.add(new BasicNameValuePair("per_page", "" + itemsPerPage)); if (type != null) { nvps.add(new BasicNameValuePair("type", type)); } nvps.add(new BasicNameValuePair("deleted", (showDeleted) ? "true" : "false")); // Prepare the URI (the host and querystring.) URI uri = URIUtils.createURI("http", "my.cl.ly", -1, "/items", URLEncodedUtils.format(nvps, "UTF-8"), null); // Prepare the request. request = new HttpGet(uri); request.addHeader("Accept", "application/json"); // Perform the request. HttpResponse response = client.execute(request); response.addHeader("Accept", "application/json"); int status = response.getStatusLine().getStatusCode(); String body = EntityUtils.toString(response.getEntity(), "UTF-8"); // We always need 200 for items retrieval. if (status == 200) { return new JSONArray(body); } // Anything else is a failure. throw new CloudApiException(status, body, null); } catch (IOException e) { LOGGER.error("Error when trying to retrieve the items.", e); throw new CloudApiException(500, e.getMessage(), e); } catch (JSONException e) { LOGGER.error("Error when trying to parse the response as JSON.", e); throw new CloudApiException(500, e.getMessage(), e); } catch (URISyntaxException e) { LOGGER.error("Error when trying to retrieve the items.", e); throw new CloudApiException(500, e.getMessage(), e); } finally { if (request != null) { request.abort(); } } }
From source file:com.nexmo.verify.sdk.NexmoVerifyClient.java
public VerifyResult verify(final String number, final String brand, final String from, final int length, final Locale locale, final LineType type) throws IOException, SAXException { if (number == null || brand == null) throw new IllegalArgumentException("number and brand parameters are mandatory."); if (length > 0 && length != 4 && length != 6) throw new IllegalArgumentException("code length must be 4 or 6."); log.debug("HTTP-Number-Verify Client .. to [ " + number + " ] brand [ " + brand + " ] "); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("api_key", this.apiKey)); params.add(new BasicNameValuePair("api_secret", this.apiSecret)); params.add(new BasicNameValuePair("number", number)); params.add(new BasicNameValuePair("brand", brand)); if (from != null) params.add(new BasicNameValuePair("sender_id", from)); if (length > 0) params.add(new BasicNameValuePair("code_length", String.valueOf(length))); if (locale != null) params.add(/* w ww . j a v a 2 s . com*/ new BasicNameValuePair("lg", (locale.getLanguage() + "-" + locale.getCountry()).toLowerCase())); if (type != null) params.add(new BasicNameValuePair("require_type", type.toString())); String verifyBaseUrl = this.baseUrl + PATH_VERIFY; // Now that we have generated a query string, we can instanciate a HttpClient, // construct a POST method and execute to submit the request String response = null; for (int pass = 1; pass <= 2; pass++) { HttpPost httpPost = new HttpPost(verifyBaseUrl); httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpUriRequest method = httpPost; String url = verifyBaseUrl + "?" + URLEncodedUtils.format(params, "utf-8"); try { if (this.httpClient == null) this.httpClient = HttpClientUtils.getInstance(this.connectionTimeout, this.soTimeout) .getNewHttpClient(); HttpResponse httpResponse = this.httpClient.execute(method); int status = httpResponse.getStatusLine().getStatusCode(); if (status != 200) throw new Exception( "got a non-200 response [ " + status + " ] from Nexmo-HTTP for url [ " + url + " ] "); response = new BasicResponseHandler().handleResponse(httpResponse); log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] "); break; } catch (Exception e) { method.abort(); log.info("communication failure: " + e); String exceptionMsg = e.getMessage(); if (exceptionMsg.indexOf("Read timed out") >= 0) { log.info( "we're still connected, but the target did not respond in a timely manner .. drop ..."); } else { if (pass == 1) { log.info("... re-establish http client ..."); this.httpClient = null; continue; } } // return a COMMS failure ... return new VerifyResult(BaseResult.STATUS_COMMS_FAILURE, null, "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e, true); } } Document doc; synchronized (this.documentBuilder) { doc = this.documentBuilder.parse(new InputSource(new StringReader(response))); } Element root = doc.getDocumentElement(); if (!"verify_response".equals(root.getNodeName())) throw new IOException("No valid response found [ " + response + "] "); return parseVerifyResult(root); }
From source file:org.jspringbot.keyword.http.HTTPHelper.java
/** * Invoke Request//from w ww .j a v a2s. c om */ public void invokeRequest() throws IOException { String actualUri = uri.getPath(); if (uri.getQuery() != null) { actualUri += "?" + uri.getQuery(); } if (CollectionUtils.isNotEmpty(params)) { if (request instanceof HttpPost) { ((HttpPost) request).setEntity(new UrlEncodedFormEntity(params, ENCODING_UTF_8)); } else { String queryString = URLEncodedUtils.format(params, ENCODING_UTF_8); if (actualUri.contains("?")) { actualUri += "&" + queryString; } else { actualUri += "?" + queryString; } if (request instanceof HttpGet) { request = new HttpGet(actualUri); } else if (request instanceof HttpPut) { request = new HttpPut(actualUri); } else if (request instanceof HttpDelete) { request = new HttpDelete(actualUri); } } } addRequestHeadersToHttpRequest(); LOG.createAppender().appendBold("Request Line:").appendCode(String.valueOf(request.getRequestLine())).log(); response = client.execute(targetHost, request, context); status = response.getStatusLine(); responseEntity = response.getEntity(); // request headers HighlightRobotLogger.HtmlAppender appender = LOG.createAppender().appendBold("Request Headers:"); for (Header header : request.getAllHeaders()) { appender.appendProperty(header.getName(), header.getValue()); } appender.log(); // request parameters for post if (request instanceof HttpPost && CollectionUtils.isNotEmpty(params)) { appender = LOG.createAppender().appendBold("Request Parameters:"); for (NameValuePair nv : params) { appender.appendProperty(nv.getName(), nv.getValue()); } appender.log(); } LOG.createAppender().appendBold("Response Status Line:").appendCode(String.valueOf(status)).log(); // response headers appender = LOG.createAppender().appendBold("Response Headers:"); for (Header header : response.getAllHeaders()) { appender.appendProperty(header.getName(), header.getValue()); } appender.log(); }
From source file:io.gs2.identifier.Gs2IdentifierClient.java
/** * ??????<br>/*from w ww .jav a 2 s .c om*/ * <br> * * @param request * @return ? */ public DescribeSecurityPolicyResult describeSecurityPolicy(DescribeSecurityPolicyRequest request) { String url = Gs2Constant.ENDPOINT_HOST + "/securityPolicy"; List<NameValuePair> queryString = new ArrayList<>(); if (request.getPageToken() != null) queryString.add(new BasicNameValuePair("pageToken", String.valueOf(request.getPageToken()))); if (request.getLimit() != null) queryString.add(new BasicNameValuePair("limit", String.valueOf(request.getLimit()))); if (queryString.size() > 0) { url += "?" + URLEncodedUtils.format(queryString, "UTF-8"); } HttpGet get = createHttpGet(url, credential, ENDPOINT, DescribeSecurityPolicyRequest.Constant.MODULE, DescribeSecurityPolicyRequest.Constant.FUNCTION); if (request.getRequestId() != null) { get.setHeader("X-GS2-REQUEST-ID", request.getRequestId()); } return doRequest(get, DescribeSecurityPolicyResult.class); }
From source file:org.apache.olingo.client.core.uri.AbstractURIBuilder.java
@Override public URI build() { final StringBuilder segmentsBuilder = new StringBuilder(); for (Segment seg : segments) { if (segmentsBuilder.length() > 0 && seg.getType() != SegmentType.KEY) { switch (seg.getType()) { case BOUND_OPERATION: segmentsBuilder.append(getBoundOperationSeparator()); break; default: if (segmentsBuilder.length() > 0 && segmentsBuilder.charAt(segmentsBuilder.length() - 1) != '/') { segmentsBuilder.append('/'); }/*from ww w. j a va2s . c o m*/ } } if (seg.getType() == SegmentType.ENTITY) { segmentsBuilder.append(seg.getType().getValue()); } else { segmentsBuilder.append(seg.getValue()); } if (seg.getType() == SegmentType.BOUND_OPERATION || seg.getType() == SegmentType.UNBOUND_OPERATION) { segmentsBuilder.append(getOperationInvokeMarker()); } } try { StringBuilder sb = segmentsBuilder; if ((queryOptions.size() + parameters.size()) > 0) { sb.append("?"); List<NameValuePair> list1 = new LinkedList<NameValuePair>(); for (Map.Entry<String, String> option : queryOptions.entrySet()) { list1.add(new BasicNameValuePair("$" + option.getKey(), option.getValue())); } for (Map.Entry<String, String> parameter : parameters.entrySet()) { list1.add(new BasicNameValuePair("@" + parameter.getKey(), parameter.getValue())); } // don't use UriBuilder.build(): // it will try to call URLEncodedUtils.format(Iterable<>,Charset) method, // which works in desktop java application, however, throws NoSuchMethodError in android OS, // so here manually construct the URL by its overload URLEncodedUtils.format(List<>,String). String queryStr = URLEncodedUtils.format(list1, "UTF-8"); sb.append(queryStr); } return URI.create(sb.toString()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Could not build valid URI", e); } }
From source file:de.geeksfactory.opacclient.apis.BaseApi.java
/** * Cleans the parameters of a URL by parsing it manually and reformatting it using {@link * URLEncodedUtils#format(java.util.List, String)} * * @param myURL the URL to clean//w w w . j a va 2 s.c o m * @return cleaned URL */ public static String cleanUrl(String myURL) { String[] parts = myURL.split("\\?"); String url = parts[0]; try { if (parts.length > 1) { url += "?"; List<NameValuePair> params = new ArrayList<>(); String[] pairs = parts[1].split("&"); for (String pair : pairs) { String[] kv = pair.split("="); if (kv.length > 1) { StringBuilder join = new StringBuilder(); for (int i = 1; i < kv.length; i++) { if (i > 1) join.append("="); join.append(kv[i]); } params.add(new BasicNameValuePair(URLDecoder.decode(kv[0], "UTF-8"), URLDecoder.decode(join.toString(), "UTF-8"))); } else { params.add(new BasicNameValuePair(URLDecoder.decode(kv[0], "UTF-8"), "")); } } url += URLEncodedUtils.format(params, "UTF-8"); } return url; } catch (UnsupportedEncodingException e) { e.printStackTrace(); return myURL; } }