List of usage examples for org.apache.http.client.utils URLEncodedUtils parse
public static List<NameValuePair> parse(final String s, final Charset charset)
From source file:com.wso2telco.proxy.entity.ServerInitiatedServiceEndpoints.java
private String getParamValueFromURL(String requiredParamName, String url) throws URISyntaxException { List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), "UTF-8"); for (NameValuePair param : params) { if (requiredParamName.equals(param.getName())) { return param.getValue(); }/* www . ja v a2s .c o m*/ } return null; }
From source file:de.geeksfactory.opacclient.apis.Bibliotheca.java
protected DetailledItem parse_result(String html) { Document doc = Jsoup.parse(html); doc.setBaseUri(opac_url);//from w ww.java 2 s . co m DetailledItem result = new DetailledItem(); if (doc.select(".detail_cover img").size() == 1) { result.setCover(doc.select(".detail_cover img").get(0).attr("src")); } result.setTitle(doc.select(".detail_titel").text()); Elements detailtrs = doc.select(".detailzeile table tr"); for (int i = 0; i < detailtrs.size(); i++) { Element tr = detailtrs.get(i); if (tr.child(0).hasClass("detail_feld")) { String title = tr.child(0).text(); String content = tr.child(1).text(); if (title.equals("Gesamtwerk:") || title.equals("Erschienen in:")) { try { if (tr.child(1).select("a").size() > 0) { Element link = tr.child(1).select("a").first(); List<NameValuePair> query = URLEncodedUtils.parse(new URI(link.absUrl("href")), "UTF-8"); for (NameValuePair q : query) { if (q.getName().equals("MedienNr")) { result.setCollectionId(q.getValue()); } } } } catch (URISyntaxException e) { } } else { if (content.contains("hier klicken") && tr.child(1).select("a").size() > 0) { content += " " + tr.child(1).select("a").first().attr("href"); } result.addDetail(new Detail(title, content)); } } } Elements detailcenterlinks = doc.select(".detailzeile_center a.detail_link"); for (int i = 0; i < detailcenterlinks.size(); i++) { Element a = detailcenterlinks.get(i); result.addDetail(new Detail(a.text().trim(), a.absUrl("href"))); } try { JSONObject copymap = new JSONObject(); if (data.has("copiestable")) { copymap = data.getJSONObject("copiestable"); } else { Elements ths = doc.select(".exemplartab .exemplarmenubar th"); for (int i = 0; i < ths.size(); i++) { Element th = ths.get(i); String head = th.text().trim(); if (head.equals("Zweigstelle")) { copymap.put("branch", i); } else if (head.equals("Abteilung")) { copymap.put("department", i); } else if (head.equals("Bereich") || head.equals("Standort")) { copymap.put("location", i); } else if (head.equals("Signatur")) { copymap.put("signature", i); } else if (head.equals("Barcode") || head.equals("Medien-Nummer")) { copymap.put("barcode", i); } else if (head.equals("Status")) { copymap.put("status", i); } else if (head.equals("Frist") || head.matches("Verf.+gbar")) { copymap.put("returndate", i); } else if (head.equals("Vorbestellungen") || head.equals("Reservierungen")) { copymap.put("reservations", i); } } } Elements exemplartrs = doc.select(".exemplartab .tabExemplar, .exemplartab .tabExemplar_"); DateTimeFormatter fmt = DateTimeFormat.forPattern("dd.MM.yyyy").withLocale(Locale.GERMAN); for (int i = 0; i < exemplartrs.size(); i++) { Element tr = exemplartrs.get(i); Copy copy = new Copy(); Iterator<?> keys = copymap.keys(); while (keys.hasNext()) { String key = (String) keys.next(); int index; try { index = copymap.has(key) ? copymap.getInt(key) : -1; } catch (JSONException e1) { index = -1; } if (index >= 0) { try { copy.set(key, tr.child(index).text(), fmt); } catch (IllegalArgumentException e) { e.printStackTrace(); } } } result.addCopy(copy); } } catch (Exception e) { e.printStackTrace(); } try { Elements bandtrs = doc.select("table .tabBand a"); for (int i = 0; i < bandtrs.size(); i++) { Element tr = bandtrs.get(i); Volume volume = new Volume(); volume.setId(tr.attr("href").split("=")[1]); volume.setTitle(tr.text()); result.addVolume(volume); } } catch (Exception e) { e.printStackTrace(); } if (doc.select(".detail_vorbest a").size() == 1) { result.setReservable(true); result.setReservation_info(doc.select(".detail_vorbest a").attr("href")); } return result; }
From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java
private List<NameValuePair> parseQueryStringAndAddToken(String queryString, String tokenToUse) { List<NameValuePair> params = URLEncodedUtils.parse(queryString, Charset.forName("UTF-8")); if (params != null) { NameValuePair tokenParam = null; for (NameValuePair param : params) { if ("token".equals(param.getName())) { tokenParam = param;// w w w . j av a 2 s . c om break; } } if (tokenParam != null) { params.remove(tokenParam); } } else { params = new ArrayList<>(); } if (tokenToUse != null) { params.add(new BasicNameValuePair("token", tokenToUse)); } return params; }
From source file:com.aipo.container.protocol.AipoDataServiceServlet.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private Map<String, String[]> loadParameters(HttpServletRequest servletRequest, Map<String, FormDataItem> formItems) { Map<String, String[]> parameterMap = new HashMap<String, String[]>(); // requestParameter??? Map<String, String[]> map = servletRequest.getParameterMap(); for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); String key = (String) entry.getKey(); String[] _value = (String[]) entry.getValue(); String[] value = new String[_value.length]; for (int i = 0; i < _value.length; i++) { value[i] = _value[i];// w ww .ja v a 2s.co m } parameterMap.put(key, value); } if (servletRequest.getContentType() != null) { // Content-type?multipart/form-data?????? if (ContentTypes.MULTIPART_FORM_CONTENT_TYPE .equals(ContentTypes.extractMimePart(servletRequest.getContentType()))) { if (formParser.isMultipartContent(servletRequest)) { Collection<FormDataItem> items = null; try { items = formParser.parse(servletRequest); } catch (IOException e) { // ignore } if (items != null) { for (FormDataItem item : items) { if (item.isFormField()) { String value = item.getAsString(); String key = item.getFieldName(); if (value != null) { try { value = new String(value.getBytes("iso-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { // ignore } } String[] valueArray = { value }; if (parameterMap.containsKey(key)) { String[] preValue = parameterMap.get(key); valueArray = Arrays.copyOf(preValue, preValue.length + 1); valueArray[preValue.length] = value; } parameterMap.put(key, valueArray); } else { formItems.put(item.getFieldName(), item); } } } } } // Content-type?application/x-www-form-urlencoded?????? if ("application/x-www-form-urlencoded" .equals(ContentTypes.extractMimePart(servletRequest.getContentType()))) { try { List<NameValuePair> params = URLEncodedUtils .parse(new URI("http://localhost:8080?" + getBodyAsString(servletRequest)), "UTF-8"); for (NameValuePair param : params) { String[] valueArray = { param.getValue() }; if (parameterMap.containsKey(param.getName())) { String[] preValue = parameterMap.get(param.getName()); valueArray = Arrays.copyOf(preValue, preValue.length + 1); valueArray[preValue.length] = param.getValue(); } parameterMap.put(param.getName(), valueArray); } } catch (URISyntaxException e) { // ignore } } } return parameterMap; }
From source file:android.webkit.cts.CtsTestServer.java
/** * Generate a response to the given request. * @throws InterruptedException/*w w w . j a v a 2s . c o m*/ * @throws IOException */ private HttpResponse getResponse(HttpRequest request) throws Exception { RequestLine requestLine = request.getRequestLine(); HttpResponse response = null; String uriString = requestLine.getUri(); Log.i(TAG, requestLine.getMethod() + ": " + uriString); synchronized (this) { mQueries.add(uriString); mLastRequestMap.put(uriString, request); if (request instanceof HttpEntityEnclosingRequest) { mRequestEntities.add(((HttpEntityEnclosingRequest) request).getEntity()); } } if (requestLine.getMethod().equals("POST")) { HttpResponse responseOnPost = onPost(request); if (responseOnPost != null) { return responseOnPost; } } URI uri = URI.create(uriString); String path = uri.getPath(); String query = uri.getQuery(); if (path.equals(FAVICON_PATH)) { path = FAVICON_ASSET_PATH; } if (path.startsWith(DELAY_PREFIX)) { String delayPath = path.substring(DELAY_PREFIX.length() + 1); String delay = delayPath.substring(0, delayPath.indexOf('/')); path = delayPath.substring(delay.length()); try { Thread.sleep(Integer.valueOf(delay)); } catch (InterruptedException ignored) { // ignore } } if (path.startsWith(AUTH_PREFIX)) { // authentication required Header[] auth = request.getHeaders("Authorization"); if ((auth.length > 0 && auth[0].getValue().equals(AUTH_CREDENTIALS)) // This is a hack to make sure that loads to this url's will always // ask for authentication. This is what the test expects. && !path.endsWith("embedded_image.html")) { // fall through and serve content path = path.substring(AUTH_PREFIX.length()); } else { // request authorization response = createResponse(HttpStatus.SC_UNAUTHORIZED); response.addHeader("WWW-Authenticate", "Basic realm=\"" + AUTH_REALM + "\""); } } if (path.startsWith(BINARY_PREFIX)) { List<NameValuePair> args = URLEncodedUtils.parse(uri, "UTF-8"); int length = 0; String mimeType = null; try { for (NameValuePair pair : args) { String name = pair.getName(); if (name.equals("type")) { mimeType = pair.getValue(); } else if (name.equals("length")) { length = Integer.parseInt(pair.getValue()); } } if (length > 0 && mimeType != null) { ByteArrayEntity entity = new ByteArrayEntity(new byte[length]); entity.setContentType(mimeType); response = createResponse(HttpStatus.SC_OK); response.setEntity(entity); response.addHeader("Content-Disposition", "attachment; filename=test.bin"); response.addHeader("Content-Type", mimeType); response.addHeader("Content-Length", "" + length); } else { // fall through, return 404 at the end } } catch (Exception e) { // fall through, return 404 at the end Log.w(TAG, e); } } else if (path.startsWith(ASSET_PREFIX)) { path = path.substring(ASSET_PREFIX.length()); // request for an asset file try { InputStream in; if (path.startsWith(RAW_PREFIX)) { String resourceName = path.substring(RAW_PREFIX.length()); int id = mResources.getIdentifier(resourceName, "raw", mContext.getPackageName()); if (id == 0) { Log.w(TAG, "Can't find raw resource " + resourceName); throw new IOException(); } in = mResources.openRawResource(id); } else { in = mAssets.open(path); } response = createResponse(HttpStatus.SC_OK); InputStreamEntity entity = new InputStreamEntity(in, in.available()); String mimeType = mMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path)); if (mimeType == null) { mimeType = "text/html"; } entity.setContentType(mimeType); response.setEntity(entity); if (query == null || !query.contains(NOLENGTH_POSTFIX)) { response.setHeader("Content-Length", "" + entity.getContentLength()); } } catch (IOException e) { response = null; // fall through, return 404 at the end } } else if (path.startsWith(REDIRECT_PREFIX)) { response = createResponse(HttpStatus.SC_MOVED_TEMPORARILY); String location = getBaseUri() + path.substring(REDIRECT_PREFIX.length()); Log.i(TAG, "Redirecting to: " + location); response.addHeader("Location", location); } else if (path.equals(QUERY_REDIRECT_PATH)) { String location = Uri.parse(uriString).getQueryParameter("dest"); if (location != null) { Log.i(TAG, "Redirecting to: " + location); response = createResponse(HttpStatus.SC_MOVED_TEMPORARILY); response.addHeader("Location", location); } } else if (path.startsWith(COOKIE_PREFIX)) { /* * Return a page with a title containing a list of all incoming cookies, * separated by '|' characters. If a numeric 'count' value is passed in a cookie, * return a cookie with the value incremented by 1. Otherwise, return a cookie * setting 'count' to 0. */ response = createResponse(HttpStatus.SC_OK); Header[] cookies = request.getHeaders("Cookie"); Pattern p = Pattern.compile("count=(\\d+)"); StringBuilder cookieString = new StringBuilder(100); cookieString.append(cookies.length); int count = 0; for (Header cookie : cookies) { cookieString.append("|"); String value = cookie.getValue(); cookieString.append(value); Matcher m = p.matcher(value); if (m.find()) { count = Integer.parseInt(m.group(1)) + 1; } } response.addHeader("Set-Cookie", "count=" + count + "; path=" + COOKIE_PREFIX); response.setEntity(createPage(cookieString.toString(), cookieString.toString())); } else if (path.startsWith(SET_COOKIE_PREFIX)) { response = createResponse(HttpStatus.SC_OK); Uri parsedUri = Uri.parse(uriString); String key = parsedUri.getQueryParameter("key"); String value = parsedUri.getQueryParameter("value"); String cookie = key + "=" + value; response.addHeader("Set-Cookie", cookie); response.setEntity(createPage(cookie, cookie)); } else if (path.startsWith(LINKED_SCRIPT_PREFIX)) { response = createResponse(HttpStatus.SC_OK); String src = Uri.parse(uriString).getQueryParameter("url"); String scriptTag = "<script src=\"" + src + "\"></script>"; response.setEntity(createPage("LinkedScript", scriptTag)); } else if (path.equals(USERAGENT_PATH)) { response = createResponse(HttpStatus.SC_OK); Header agentHeader = request.getFirstHeader("User-Agent"); String agent = ""; if (agentHeader != null) { agent = agentHeader.getValue(); } response.setEntity(createPage(agent, agent)); } else if (path.equals(TEST_DOWNLOAD_PATH)) { response = createTestDownloadResponse(Uri.parse(uriString)); } else if (path.equals(SHUTDOWN_PREFIX)) { response = createResponse(HttpStatus.SC_OK); // We cannot close the socket here, because we need to respond. // Status must be set to OK, or else the test will fail due to // a RunTimeException. } else if (path.equals(APPCACHE_PATH)) { response = createResponse(HttpStatus.SC_OK); response.setEntity(createEntity("<!DOCTYPE HTML>" + "<html manifest=\"appcache.manifest\">" + " <head>" + " <title>Waiting</title>" + " <script>" + " function updateTitle(x) { document.title = x; }" + " window.applicationCache.onnoupdate = " + " function() { updateTitle(\"onnoupdate Callback\"); };" + " window.applicationCache.oncached = " + " function() { updateTitle(\"oncached Callback\"); };" + " window.applicationCache.onupdateready = " + " function() { updateTitle(\"onupdateready Callback\"); };" + " window.applicationCache.onobsolete = " + " function() { updateTitle(\"onobsolete Callback\"); };" + " window.applicationCache.onerror = " + " function() { updateTitle(\"onerror Callback\"); };" + " </script>" + " </head>" + " <body onload=\"updateTitle('Loaded');\">AppCache test</body>" + "</html>")); } else if (path.equals(APPCACHE_MANIFEST_PATH)) { response = createResponse(HttpStatus.SC_OK); try { StringEntity entity = new StringEntity("CACHE MANIFEST"); // This entity property is not used when constructing the response, (See // AbstractMessageWriter.write(), which is called by // AbstractHttpServerConnection.sendResponseHeader()) so we have to set this header // manually. // TODO: Should we do this for all responses from this server? entity.setContentType("text/cache-manifest"); response.setEntity(entity); response.setHeader("Content-Type", "text/cache-manifest"); } catch (UnsupportedEncodingException e) { Log.w(TAG, "Unexpected UnsupportedEncodingException"); } } if (response == null) { response = createResponse(HttpStatus.SC_NOT_FOUND); } StatusLine sl = response.getStatusLine(); Log.i(TAG, sl.getStatusCode() + "(" + sl.getReasonPhrase() + ")"); setDateHeaders(response); return response; }
From source file:org.apache.nifi.processors.aws.wag.AbstractAWSGatewayApiProcessor.java
/** * Returns a map of Query Parameter Name to Values * * @param context ProcessContext/*from w w w .j av a 2s . c o m*/ * @return Map of names and values */ protected Map<String, List<String>> getParameters(ProcessContext context) { if (!context.getProperty(PROP_QUERY_PARAMS).isSet()) { return new HashMap<>(); } final String queryString = context.getProperty(PROP_QUERY_PARAMS).evaluateAttributeExpressions().getValue(); List<NameValuePair> params = URLEncodedUtils.parse(queryString, Charsets.toCharset("UTF-8")); if (params.isEmpty()) { return new HashMap<>(); } Map<String, List<String>> map = new HashMap<>(); for (NameValuePair nvp : params) { if (!map.containsKey(nvp.getName())) { map.put(nvp.getName(), new ArrayList<>()); } map.get(nvp.getName()).add(nvp.getValue()); } return map; }
From source file:com.bzcentre.dapiPush.DapiReceiver.java
public static Map<String, Object> convertQueryStringToMap(String url) throws URISyntaxException { List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), Charset.defaultCharset()); Map<String, Object> queryStringMap = new HashMap<>(); for (NameValuePair param : params) { queryStringMap.put(param.getName(), handleMultiValuedQueryParam(queryStringMap, param.getName(), param.getValue())); }// w ww.j a v a2 s.c o m return queryStringMap; }
From source file:org.keycloak.testsuite.util.OAuthClient.java
public Map<String, String> getCurrentFragment() { Map<String, String> m = new HashMap<>(); String fragment = getCurrentUri().getRawFragment(); List<NameValuePair> pairs = (fragment == null || fragment.isEmpty()) ? Collections.emptyList() : URLEncodedUtils.parse(fragment, Charset.forName("UTF-8")); for (NameValuePair p : pairs) { m.put(p.getName(), p.getValue()); }//from w w w .jav a2 s. c o m return m; }