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.ibm.ws.lars.rest.RepositoryContext.java
protected void doPostBadAttachmentNoContent(String assetId, String name, Attachment attachment, int expectedRC, String expectedMessage) throws ClientProtocolException, IOException, InvalidJsonAssetException { List<NameValuePair> qparams = new ArrayList<>(); qparams.add(new BasicNameValuePair("name", name)); String url = "/assets/" + assetId + "/attachments?" + URLEncodedUtils.format(qparams, "UTF-8"); String message = doPost(url, attachment.toJson(), expectedRC); if (expectedMessage != null) { String errorMessage = parseErrorObject(message.toString()); assertEquals("Unexpected message from server", expectedMessage, errorMessage); }//from w w w . j a va 2 s .c om }
From source file:com.arangodb.http.HttpManager.java
public static String buildUrl(String baseUrl, HttpRequestEntity requestEntity) { if (requestEntity.parameters != null && !requestEntity.parameters.isEmpty()) { String paramString = URLEncodedUtils.format(toList(requestEntity.parameters), "utf-8"); if (requestEntity.url.contains("?")) { return baseUrl + requestEntity.url + "&" + paramString; } else {/*from ww w .j a va 2s . c o m*/ return baseUrl + requestEntity.url + "?" + paramString; } } return baseUrl + requestEntity.url; }
From source file:tw.com.sti.store.api.android.AndroidApiService.java
/** * Comments of Application(08): ?// w ww .j ava 2 s .c o m */ public ApiInvoker<CommentsRet> appComments(String packageName, int page, Integer pSize) { String url = apiUrl.getApplicationCommentsUrl(packageName, page); ApiDataParseHandler<CommentsRet> handler = ApiDataParseHandler.COMMENTS_RET_PARSE_HANDLER; String[] paramNames = null; String[] paramValues = null; if (pSize != null) { paramNames = new String[] { "psize" }; paramValues = new String[] { pSize.toString() }; } List<NameValuePair> nvps = createRequestParams(paramNames, paramValues, true); if (Logger.DEBUG) { L.d(url + "?" + URLEncodedUtils.format(nvps, "UTF-8")); } return new ApiInvoker<CommentsRet>(this.config, handler, url, nvps); }
From source file:com.ibm.ws.lars.rest.RepositoryContext.java
protected Attachment doPostAttachmentWithContent(String assetId, String name, Attachment attachment, byte[] content, ContentType contentType) throws ClientProtocolException, IOException, InvalidJsonAssetException { List<NameValuePair> qparams = new ArrayList<>(); qparams.add(new BasicNameValuePair("name", name)); String url = "/assets/" + assetId + "/attachments?" + URLEncodedUtils.format(qparams, "UTF-8"); String response = doPostMultipart(url, name, attachment.toJson(), content, contentType, 200); return Attachment.jsonToAttachment(response); }
From source file:io.gs2.matchmaking.Gs2MatchmakingClient.java
/** * ??????<br>//from ww w. j a v a2s . c om * <br> * * @param request * @return ? */ public DescribeMatchmakingResult describeMatchmaking(DescribeMatchmakingRequest request) { String url = Gs2Constant.ENDPOINT_HOST + "/matchmaking"; 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, DescribeMatchmakingRequest.Constant.MODULE, DescribeMatchmakingRequest.Constant.FUNCTION); if (request.getRequestId() != null) { get.setHeader("X-GS2-REQUEST-ID", request.getRequestId()); } return doRequest(get, DescribeMatchmakingResult.class); }
From source file:org.auraframework.integration.test.util.AuraHttpTestCase.java
/** * Build a URL for a get from the given parameters with all the standard parameters set from a descriptor. * * This is a convenience function to make gets more consistent. It sets: * <ul>/*w w w .j ava 2 s . c o m*/ * <li>aura.tag: the name of the descriptor to get.</li> * <li>aura.defType: the type of the descriptor.</li> * <li>aura.context: the context, including * <ul> * <li>loaded: the descriptor + type from above.</li> * <li>fwUID: the framework UID</li> * <li>mode: from the parameters</li> * <li>format: from the parameters</li> * </ul> * </li> * </ul> * * @param mode the Aura mode to use. * @param format the format (HTML vs JSON) to use * @param desc the descriptor to set as the primary object. * @param params extra parameters to set. * @param headers extra headers. */ protected HttpGet obtainAuraGetMethod(Mode mode, Format format, DefDescriptor<? extends BaseComponentDef> desc, Map<String, String> params, Header[] headers) throws QuickFixException, MalformedURLException, URISyntaxException { List<NameValuePair> urlparams = Lists.newArrayList(); urlparams.add( new BasicNameValuePair("aura.tag", String.format("%s:%s", desc.getNamespace(), desc.getName()))); urlparams.add(new BasicNameValuePair("aura.defType", desc.getDefType().toString())); for (Map.Entry<String, String> entry : params.entrySet()) { urlparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } urlparams.add(new BasicNameValuePair("aura.context", getAuraTestingUtil().getContextURL(mode, format, desc, false))); String query = URLEncodedUtils.format(urlparams, "UTF-8"); // final url Request to be send to server return obtainGetMethod("aura?" + query, true, headers); }
From source file:org.b3log.latke.client.LatkeClient.java
/** * Gets repository names.//from ww w .ja v a2 s . com * * @return repository names * @throws Exception exception */ private static Set<String> getRepositoryNames() throws Exception { final HttpClient httpClient = new DefaultHttpClient(); final List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("userName", userName)); qparams.add(new BasicNameValuePair("password", password)); final URI uri = URIUtils.createURI("http", serverAddress, -1, GET_REPOSITORY_NAMES, URLEncodedUtils.format(qparams, "UTF-8"), null); final HttpGet request = new HttpGet(); request.setURI(uri); if (verbose) { System.out.println("Getting repository names[" + GET_REPOSITORY_NAMES + "]"); } final HttpResponse httpResponse = httpClient.execute(request); final InputStream contentStream = httpResponse.getEntity().getContent(); final String content = IOUtils.toString(contentStream).trim(); if (verbose) { printResponse(content); } final JSONObject result = new JSONObject(content); final JSONArray repositoryNames = result.getJSONArray("repositoryNames"); final Set<String> ret = new HashSet<String>(); for (int i = 0; i < repositoryNames.length(); i++) { final String repositoryName = repositoryNames.getString(i); ret.add(repositoryName); final File dir = new File(backupDir.getPath() + File.separatorChar + repositoryName); if (!dir.exists() && verbose) { dir.mkdir(); System.out.println("Created a directory[name=" + dir.getName() + "] under backup directory[path=" + backupDir.getPath() + "]"); } } return ret; }
From source file:com.mars.framework.volley.request.Request.java
protected static String getUrlWithQueryString(String url, Map<String, String> params) { if (!TextUtils.isEmpty(url) && params != null && params.size() != 0) { List<BasicNameValuePair> paramsList = new LinkedList<BasicNameValuePair>(); for (ConcurrentHashMap.Entry<String, String> entry : params.entrySet()) { paramsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); }//from ww w . ja v a 2 s . co m String paramsString = URLEncodedUtils.format(paramsList, DEFAULT_PARAMS_ENCODING); if (url.indexOf("?") == -1) { url += "?" + paramsString; } else { url += "&" + paramsString; } } return url; }
From source file:de.geeksfactory.opacclient.apis.TouchPoint.java
protected SearchRequestResult parse_search(String html, int page) throws OpacErrorException, IOException { Document doc = Jsoup.parse(html); if (doc.select("#RefineHitListForm").size() > 0) { // the results are located on a different page loaded via AJAX html = httpGet(opac_url + "/speedHitList.do?_=" + String.valueOf(System.currentTimeMillis() / 1000) + "&hitlistindex=0&exclusionList=", ENCODING); doc = Jsoup.parse(html);/* ww w . ja v a 2s . com*/ } if (doc.select(".nodata").size() > 0) { return new SearchRequestResult(new ArrayList<SearchResult>(), 0, 1, 1); } doc.setBaseUri(opac_url + "/searchfoo"); int results_total = -1; String resultnumstr = doc.select(".box-header h2").first().text(); if (resultnumstr.contains("(1/1)") || resultnumstr.contains(" 1/1")) { reusehtml = html; throw new OpacErrorException("is_a_redirect"); } else if (resultnumstr.contains("(")) { results_total = Integer.parseInt(resultnumstr.replaceAll(".*\\(([0-9]+)\\).*", "$1")); } else if (resultnumstr.contains(": ")) { results_total = Integer.parseInt(resultnumstr.replaceAll(".*: ([0-9]+)$", "$1")); } Elements table = doc.select("table.data > tbody > tr"); identifier = null; Elements links = doc.select("table.data a"); boolean haslink = false; for (Element node : links) { if (node.hasAttr("href") & node.attr("href").contains("singleHit.do") && !haslink) { haslink = true; try { List<NameValuePair> anyurl = URLEncodedUtils .parse(new URI(node.attr("href").replace(" ", "%20").replace("&", "&")), ENCODING); for (NameValuePair nv : anyurl) { if (nv.getName().equals("identifier")) { identifier = nv.getValue(); break; } } } catch (Exception e) { e.printStackTrace(); } } } List<SearchResult> results = new ArrayList<>(); for (int i = 0; i < table.size(); i++) { Element tr = table.get(i); SearchResult sr = new SearchResult(); if (tr.select(".icn, img[width=32]").size() > 0) { String[] fparts = tr.select(".icn, img[width=32]").first().attr("src").split("/"); String fname = fparts[fparts.length - 1]; String changedFname = fname.toLowerCase(Locale.GERMAN).replace(".jpg", "").replace(".gif", "") .replace(".png", ""); // File names can look like this: "20_DVD_Video.gif" Pattern pattern = Pattern.compile("(\\d+)_.*"); Matcher matcher = pattern.matcher(changedFname); if (matcher.find()) { changedFname = matcher.group(1); } MediaType defaulttype = defaulttypes.get(changedFname); if (data.has("mediatypes")) { try { sr.setType(MediaType.valueOf(data.getJSONObject("mediatypes").getString(fname))); } catch (JSONException | IllegalArgumentException e) { sr.setType(defaulttype); } } else { sr.setType(defaulttype); } } String title; String text; if (tr.select(".results table").size() > 0) { // e.g. RWTH Aachen title = tr.select(".title a").text(); text = tr.select(".title div").text(); } else { // e.g. Schaffhausen, BSB Mnchen title = tr.select(".title, .hitlistTitle").text(); text = tr.select(".results, .hitlistMetadata").first().ownText(); } // we need to do some evil javascript parsing here to get the cover // and loan status of the item // get cover if (tr.select(".cover script").size() > 0) { String js = tr.select(".cover script").first().html(); String isbn = matchJSVariable(js, "isbn"); String ajaxUrl = matchJSVariable(js, "ajaxUrl"); if (!"".equals(isbn) && !"".equals(ajaxUrl)) { String url = new URL(new URL(opac_url + "/"), ajaxUrl).toString(); String coverUrl = httpGet(url + "?isbn=" + isbn + "&size=small", ENCODING); if (!"".equals(coverUrl)) { sr.setCover(coverUrl.replace("\r\n", "").trim()); } } } // get loan status and media ID if (tr.select("div[id^=loanstatus] + script").size() > 0) { String js = tr.select("div[id^=loanstatus] + script").first().html(); String[] variables = new String[] { "loanstateDBId", "itemIdentifier", "hitlistIdentifier", "hitlistPosition", "duplicateHitlistIdentifier", "itemType", "titleStatus", "typeofHit", "context" }; String ajaxUrl = matchJSVariable(js, "ajaxUrl"); if (!"".equals(ajaxUrl)) { JSONObject id = new JSONObject(); List<NameValuePair> map = new ArrayList<>(); for (String variable : variables) { String value = matchJSVariable(js, variable); if (!"".equals(value)) { map.add(new BasicNameValuePair(variable, value)); } try { if (variable.equals("itemIdentifier")) { id.put("id", value); } else if (variable.equals("loanstateDBId")) { id.put("db", value); } } catch (JSONException e) { e.printStackTrace(); } } sr.setId(id.toString()); String url = new URL(new URL(opac_url + "/"), ajaxUrl).toString(); String loanStatusHtml = httpGet(url + "?" + URLEncodedUtils.format(map, "UTF-8"), ENCODING) .replace("\r\n", "").trim(); Document loanStatusDoc = Jsoup.parse(loanStatusHtml); String loanstatus = loanStatusDoc.text().replace("\u00bb", "").trim(); if ((loanstatus.startsWith("entliehen") && loanstatus.contains("keine Vormerkung mglich") || loanstatus.contains("Keine Exemplare verfgbar"))) { sr.setStatus(SearchResult.Status.RED); } else if (loanstatus.startsWith("entliehen") || loanstatus.contains("andere Zweigstelle")) { sr.setStatus(SearchResult.Status.YELLOW); } else if ((loanstatus.startsWith("bestellbar") && !loanstatus.contains("nicht bestellbar")) || (loanstatus.startsWith("vorbestellbar") && !loanstatus.contains("nicht vorbestellbar")) || (loanstatus.startsWith("vorbestellbar") && !loanstatus.contains("nicht vorbestellbar")) || (loanstatus.startsWith("vormerkbar") && !loanstatus.contains("nicht vormerkbar")) || (loanstatus.contains("heute zurckgebucht")) || (loanstatus.contains("ausleihbar") && !loanstatus.contains("nicht ausleihbar"))) { sr.setStatus(SearchResult.Status.GREEN); } if (sr.getType() != null) { if (sr.getType().equals(MediaType.EBOOK) || sr.getType().equals(MediaType.EVIDEO) || sr.getType().equals(MediaType.MP3)) // Especially Onleihe.de ebooks are often marked // green though they are not available. { sr.setStatus(SearchResult.Status.UNKNOWN); } } } } sr.setInnerhtml(("<b>" + title + "</b><br/>") + text); sr.setNr(10 * (page - 1) + i + 1); results.add(sr); } resultcount = results.size(); return new SearchRequestResult(results, results_total, page); }
From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java
@Override public String obtainOauth2Code(String destinationUrl) throws IllegalArgumentException { URI nakedUri;/*from ww w . j a v a2 s . c o m*/ try { nakedUri = new URI(authUrl); } catch (URISyntaxException e2) { e2.printStackTrace(); logger.error(e2.toString()); return getSelfUrl(); } addCredentials(CLIENT_ID, CLIENT_SECRET, nakedUri.getHost()); Context ctxt = new Context(); stateMap.put(ctxt.getKey(), ctxt); ctxtKey = ctxt.getKey(); List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("response_type", "code")); qparams.add(new BasicNameValuePair("client_id", CLIENT_ID)); qparams.add(new BasicNameValuePair("scope", scope)); qparams.add(new BasicNameValuePair("redirect_uri", getOauth2CallbackUrl())); qparams.add(new BasicNameValuePair("state", ctxt.getKey())); URI uri; try { uri = URIUtils.createURI(nakedUri.getScheme(), nakedUri.getHost(), nakedUri.getPort(), nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null); } catch (URISyntaxException e1) { e1.printStackTrace(); logger.error(e1.toString()); return getSelfUrl(); } String toString = uri.toString(); return toString; }