List of usage examples for java.net URL getQuery
public String getQuery()
From source file:com.rsltc.profiledata.main.MainActivity.java
public static Map<String, List<String>> splitQuery(URL url) throws UnsupportedEncodingException { final Map<String, List<String>> query_pairs = new LinkedHashMap<String, List<String>>(); final String[] pairs = url.getQuery().split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair; if (!query_pairs.containsKey(key)) { query_pairs.put(key, new LinkedList<String>()); }// w w w . java 2s . co m final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null; query_pairs.get(key).add(value); } return query_pairs; }
From source file:com.echopf.ECHOQuery.java
/** * Sends a HTTP request with optional request contents/parameters. * @param path a request url path/* w ww .ja v a 2s . c om*/ * @param httpMethod a request method (GET/POST/PUT/DELETE) * @param data request contents/parameters * @param multipart use multipart/form-data to encode the contents * @throws ECHOException */ public static InputStream requestRaw(String path, String httpMethod, JSONObject data, boolean multipart) throws ECHOException { final String secureDomain = ECHO.secureDomain; if (secureDomain == null) throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`."); String baseUrl = new StringBuilder("https://").append(secureDomain).toString(); String url = new StringBuilder(baseUrl).append("/").append(path).toString(); HttpsURLConnection httpClient = null; try { URL urlObj = new URL(url); StringBuilder apiUrl = new StringBuilder(baseUrl).append(urlObj.getPath()).append("/rest_api=1.0/"); // Append the QueryString contained in path boolean isContainQuery = urlObj.getQuery() != null; if (isContainQuery) apiUrl.append("?").append(urlObj.getQuery()); // Append the QueryString from data if (httpMethod.equals("GET") && data != null) { boolean firstItem = true; Iterator<?> iter = data.keys(); while (iter.hasNext()) { if (firstItem && !isContainQuery) { firstItem = false; apiUrl.append("?"); } else { apiUrl.append("&"); } String key = (String) iter.next(); String value = data.optString(key); apiUrl.append(key); apiUrl.append("="); apiUrl.append(value); } } URL urlConn = new URL(apiUrl.toString()); httpClient = (HttpsURLConnection) urlConn.openConnection(); } catch (IOException e) { throw new ECHOException(e); } final String appId = ECHO.appId; final String appKey = ECHO.appKey; final String accessToken = ECHO.accessToken; if (appId == null || appKey == null) throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`."); InputStream responseInputStream = null; try { httpClient.setRequestMethod(httpMethod); httpClient.addRequestProperty("X-ECHO-APP-ID", appId); httpClient.addRequestProperty("X-ECHO-APP-KEY", appKey); // Set access token if (accessToken != null && !accessToken.isEmpty()) httpClient.addRequestProperty("X-ECHO-ACCESS-TOKEN", accessToken); // Build content if (!httpMethod.equals("GET") && data != null) { httpClient.setDoOutput(true); httpClient.setChunkedStreamingMode(0); // use default chunk size if (multipart == false) { // application/json httpClient.addRequestProperty("CONTENT-TYPE", "application/json"); BufferedWriter wrBuffer = new BufferedWriter( new OutputStreamWriter(httpClient.getOutputStream())); wrBuffer.write(data.toString()); wrBuffer.close(); } else { // multipart/form-data final String boundary = "*****" + UUID.randomUUID().toString() + "*****"; final String twoHyphens = "--"; final String lineEnd = "\r\n"; final int maxBufferSize = 1024 * 1024 * 3; httpClient.setRequestMethod("POST"); httpClient.addRequestProperty("CONTENT-TYPE", "multipart/form-data; boundary=" + boundary); final DataOutputStream outputStream = new DataOutputStream(httpClient.getOutputStream()); try { JSONObject postData = new JSONObject(); postData.putOpt("method", httpMethod); postData.putOpt("data", data); new Object() { public void post(JSONObject data, List<String> currentKeys) throws JSONException, IOException { Iterator<?> keys = data.keys(); while (keys.hasNext()) { String key = (String) keys.next(); List<String> newKeys = new ArrayList<String>(currentKeys); newKeys.add(key); Object val = data.get(key); // convert JSONArray into JSONObject if (val instanceof JSONArray) { JSONArray array = (JSONArray) val; JSONObject val2 = new JSONObject(); for (Integer i = 0; i < array.length(); i++) { val2.putOpt(i.toString(), array.get(i)); } val = val2; } // build form-data name String name = ""; for (int i = 0; i < newKeys.size(); i++) { String key2 = newKeys.get(i); name += (i == 0) ? key2 : "[" + key2 + "]"; } if (val instanceof ECHOFile) { ECHOFile file = (ECHOFile) val; if (file.getLocalBytes() == null) continue; InputStream fileInputStream = new ByteArrayInputStream( file.getLocalBytes()); if (fileInputStream != null) { String mimeType = URLConnection .guessContentTypeFromName(file.getFileName()); // write header outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + file.getFileName() + "\"" + lineEnd); outputStream.writeBytes("Content-Type: " + mimeType + lineEnd); outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); outputStream.writeBytes(lineEnd); // write content int bytesAvailable, bufferSize, bytesRead; do { bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); if (bytesRead <= 0) break; outputStream.write(buffer, 0, bufferSize); } while (true); fileInputStream.close(); outputStream.writeBytes(lineEnd); } } else if (val instanceof JSONObject) { this.post((JSONObject) val, newKeys); } else { String data2 = null; try { // in case of boolean boolean bool = data.getBoolean(key); data2 = bool ? "true" : ""; } catch (JSONException e) { // if the value is not a Boolean or the String "true" or "false". data2 = val.toString().trim(); } // write header outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes( "Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd); outputStream .writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd); outputStream.writeBytes("Content-Length: " + data2.length() + lineEnd); outputStream.writeBytes(lineEnd); // write content byte[] bytes = data2.getBytes(); for (int i = 0; i < bytes.length; i++) { outputStream.writeByte(bytes[i]); } outputStream.writeBytes(lineEnd); } } } }.post(postData, new ArrayList<String>()); } catch (JSONException e) { throw new ECHOException(e); } finally { outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.flush(); outputStream.close(); } } } else { httpClient.addRequestProperty("CONTENT-TYPE", "application/json"); } if (httpClient.getResponseCode() != -1 /*== HttpURLConnection.HTTP_OK*/) { responseInputStream = httpClient.getInputStream(); } } catch (IOException e) { // get http response code int errorCode = -1; try { errorCode = httpClient.getResponseCode(); } catch (IOException e1) { throw new ECHOException(e1); } // get error contents JSONObject responseObj; try { String jsonStr = ECHOQuery.getResponseString(httpClient.getErrorStream()); responseObj = new JSONObject(jsonStr); } catch (JSONException e1) { if (errorCode == 404) { throw new ECHOException(ECHOException.RESOURCE_NOT_FOUND, "Resource not found."); } throw new ECHOException(ECHOException.INVALID_JSON_FORMAT, "Invalid JSON format."); } // if (responseObj != null) { int code = responseObj.optInt("error_code"); String message = responseObj.optString("error_message"); if (code != 0 || !message.equals("")) { JSONObject details = responseObj.optJSONObject("error_details"); if (details == null) { throw new ECHOException(code, message); } else { throw new ECHOException(code, message, details); } } } throw new ECHOException(e); } return responseInputStream; }
From source file:com.odoko.solrcli.actions.CrawlPostAction.java
/** * Appends to the path of the URL//from w w w . ja v a2 s .c o m * @param url the URL * @param append the path to append * @return the final URL version */ protected static URL appendUrlPath(URL url, String append) throws MalformedURLException { return new URL(url.getProtocol() + "://" + url.getAuthority() + url.getPath() + append + (url.getQuery() != null ? "?"+url.getQuery() : "")); }
From source file:org.opennms.netmgt.provision.service.dns.DnsRequisitionUrlConnection.java
/** * Validate the format is:// w ww .j av a 2s .com * dns://<host>/<zone>/?expression=<regex> * * there should be only one arguement in the path * there should only be one query parameter * * @param url a {@link java.net.URL} object. * @throws java.net.MalformedURLException if any. */ protected static void validateDnsUrl(URL url) throws MalformedURLException { String path = url.getPath(); path = StringUtils.removeStart(path, "/"); path = StringUtils.removeEnd(path, "/"); if (path == null || StringUtils.countMatches(path, "/") > 1) { throw new MalformedURLException("The specified DNS URL contains invalid path: " + url); } String query = url.getQuery(); if ((query != null) && (determineExpressionFromUrl(url) == null) && (getArgs().get(SERVICES_ARG) == null) && (getArgs().get(FID_HASH_SRC_ARG) == null)) { throw new MalformedURLException("The specified DNS URL contains an invalid query string: " + url); } }
From source file:com.gargoylesoftware.htmlunit.util.UrlUtils.java
/** * Creates and returns a new URL identical to the specified URL, except using the specified reference. * @param u the URL on which to base the returned URL * @param newRef the new reference to use in the returned URL * @return a new URL identical to the specified URL, except using the specified reference * @throws MalformedURLException if there is a problem creating the new URL *///from ww w .j av a 2s. c o m public static URL getUrlWithNewRef(final URL u, final String newRef) throws MalformedURLException { return createNewUrl(u.getProtocol(), u.getAuthority(), u.getPath(), newRef, u.getQuery()); }
From source file:com.gargoylesoftware.htmlunit.util.UrlUtils.java
/** * Creates and returns a new URL identical to the specified URL, except using the specified path. * @param u the URL on which to base the returned URL * @param newPath the new path to use in the returned URL * @return a new URL identical to the specified URL, except using the specified path * @throws MalformedURLException if there is a problem creating the new URL *//*from w w w . j a v a 2s. com*/ public static URL getUrlWithNewPath(final URL u, final String newPath) throws MalformedURLException { return createNewUrl(u.getProtocol(), u.getAuthority(), newPath, u.getRef(), u.getQuery()); }
From source file:com.gargoylesoftware.htmlunit.util.UrlUtils.java
/** * Creates and returns a new URL identical to the specified URL, except using the specified protocol. * @param u the URL on which to base the returned URL * @param newProtocol the new protocol to use in the returned URL * @return a new URL identical to the specified URL, except using the specified protocol * @throws MalformedURLException if there is a problem creating the new URL *//*from w ww . j ava 2 s . com*/ public static URL getUrlWithNewProtocol(final URL u, final String newProtocol) throws MalformedURLException { return createNewUrl(newProtocol, u.getAuthority(), u.getPath(), u.getRef(), u.getQuery()); }
From source file:org.opendatakit.briefcase.util.XmlManipulationUtils.java
public static final List<RemoteFormDefinition> parseFormListResponse(boolean isOpenRosaResponse, Document formListDoc) throws ParsingException { // This gets a list of available forms from the specified server. List<RemoteFormDefinition> formList = new ArrayList<RemoteFormDefinition>(); if (isOpenRosaResponse) { // Attempt OpenRosa 1.0 parsing Element xformsElement = formListDoc.getRootElement(); if (!xformsElement.getName().equals("xforms")) { logger.error("Parsing OpenRosa reply -- root element is not <xforms> :" + xformsElement.getName()); throw new ParsingException(BAD_OPENROSA_FORMLIST); }/*from ww w . j a v a 2 s .c om*/ String namespace = xformsElement.getNamespace(); if (!isXformsListNamespacedElement(xformsElement)) { logger.error("Parsing OpenRosa reply -- root element namespace is incorrect:" + namespace); throw new ParsingException(BAD_OPENROSA_FORMLIST); } int nElements = xformsElement.getChildCount(); for (int i = 0; i < nElements; ++i) { if (xformsElement.getType(i) != Element.ELEMENT) { // e.g., whitespace (text) continue; } Element xformElement = (Element) xformsElement.getElement(i); if (!isXformsListNamespacedElement(xformElement)) { // someone else's extension? continue; } String name = xformElement.getName(); if (!name.equalsIgnoreCase("xform")) { // someone else's extension? continue; } // this is something we know how to interpret String formId = null; String formName = null; String version = null; String majorMinorVersion = null; String description = null; String downloadUrl = null; String manifestUrl = null; // don't process descriptionUrl int fieldCount = xformElement.getChildCount(); for (int j = 0; j < fieldCount; ++j) { if (xformElement.getType(j) != Element.ELEMENT) { // whitespace continue; } Element child = xformElement.getElement(j); if (!isXformsListNamespacedElement(child)) { // someone else's extension? continue; } String tag = child.getName(); if (tag.equals("formID")) { formId = XFormParser.getXMLText(child, true); if (formId != null && formId.length() == 0) { formId = null; } } else if (tag.equals("name")) { formName = XFormParser.getXMLText(child, true); if (formName != null && formName.length() == 0) { formName = null; } } else if (tag.equals("version")) { version = XFormParser.getXMLText(child, true); if (version != null && version.length() == 0) { version = null; } } else if (tag.equals("majorMinorVersion")) { majorMinorVersion = XFormParser.getXMLText(child, true); if (majorMinorVersion != null && majorMinorVersion.length() == 0) { majorMinorVersion = null; } } else if (tag.equals("descriptionText")) { description = XFormParser.getXMLText(child, true); if (description != null && description.length() == 0) { description = null; } } else if (tag.equals("downloadUrl")) { downloadUrl = XFormParser.getXMLText(child, true); if (downloadUrl != null && downloadUrl.length() == 0) { downloadUrl = null; } } else if (tag.equals("manifestUrl")) { manifestUrl = XFormParser.getXMLText(child, true); if (manifestUrl != null && manifestUrl.length() == 0) { manifestUrl = null; } } } if (formId == null || downloadUrl == null || formName == null) { logger.error("Parsing OpenRosa reply -- Forms list entry " + Integer.toString(i) + " is missing one or more tags: formId, name, or downloadUrl"); formList.clear(); throw new ParsingException(BAD_OPENROSA_FORMLIST); } String versionString = null; if (version != null && version.length() != 0) { versionString = version; } else if (majorMinorVersion != null && majorMinorVersion.length() != 0) { int idx = majorMinorVersion.indexOf("."); if (idx == -1) { versionString = majorMinorVersion; } else { versionString = majorMinorVersion.substring(0, idx); } } try { if (versionString != null) { // verify that the version string is a long integer value... Long.parseLong(versionString); } } catch (Exception e) { e.printStackTrace(); logger.error("Parsing OpenRosa reply -- Forms list entry " + Integer.toString(i) + " has an invalid version string: " + versionString); formList.clear(); throw new ParsingException(BAD_OPENROSA_FORMLIST); } formList.add(new RemoteFormDefinition(formName, formId, versionString, downloadUrl, manifestUrl)); } } else { // Aggregate 0.9.x mode... // populate HashMap with form names and urls Element formsElement = formListDoc.getRootElement(); int formsCount = formsElement.getChildCount(); for (int i = 0; i < formsCount; ++i) { if (formsElement.getType(i) != Element.ELEMENT) { // whitespace continue; } Element child = formsElement.getElement(i); String tag = child.getName(); if (tag.equalsIgnoreCase("form")) { String formName = XFormParser.getXMLText(child, true); if (formName != null && formName.length() == 0) { formName = null; } String downloadUrl = child.getAttributeValue(null, "url"); downloadUrl = downloadUrl.trim(); if (downloadUrl != null && downloadUrl.length() == 0) { downloadUrl = null; } if (downloadUrl == null || formName == null) { logger.error("Parsing OpenRosa reply -- Forms list entry " + Integer.toString(i) + " is missing form name or url attribute"); formList.clear(); throw new ParsingException(BAD_LEGACY_FORMLIST); } // Since this is ODK Aggregate 0.9.8 or higher, we know that the // formId is // given as a parameter of the URL... String formId = null; try { URL url = new URL(downloadUrl); String qs = url.getQuery(); if (qs.startsWith(ODK_ID_PARAMETER_EQUALS)) { formId = qs.substring(ODK_ID_PARAMETER_EQUALS.length()); } } catch (MalformedURLException e) { e.printStackTrace(); } if (formId == null) { throw new ParsingException( "Unable to extract formId from download URL of legacy 0.9.8 server"); } formList.add(new RemoteFormDefinition(formName, formId, null, downloadUrl, null)); } } } return formList; }
From source file:org.mycore.common.xml.MCRXMLFunctions.java
/** * Encodes the given URL so, that it is a valid RFC 2396 URL. *//*from www . java 2s. c om*/ public static String normalizeAbsoluteURL(String url) throws MalformedURLException, URISyntaxException { try { return new URI(url).toASCIIString(); } catch (Exception e) { URL testURL = new URL(url); URI uri = new URI(testURL.getProtocol(), testURL.getUserInfo(), testURL.getHost(), testURL.getPort(), testURL.getPath(), testURL.getQuery(), testURL.getRef()); return uri.toASCIIString(); } }
From source file:eionet.cr.util.URLUtil.java
/** * * @param urlString//w w w . j av a2 s. co m * @return */ public static String normalizeUrl(String urlString) { // if given URL string is null, return it as it is if (urlString == null) { return urlString; } // we're going to need both the URL and URI wrappers URL url = null; URI uri = null; try { url = new URL(urlString.trim()); uri = url.toURI(); } catch (MalformedURLException e) { return urlString; } catch (URISyntaxException e) { return urlString; } // get all the various parts of this URL String protocol = url.getProtocol(); String userInfo = url.getUserInfo(); String host = url.getHost(); int port = url.getPort(); String path = url.getPath(); String query = url.getQuery(); String reference = url.getRef(); // start building the result, processing each of the above-found URL parts StringBuilder result = new StringBuilder(); try { if (!StringUtils.isEmpty(protocol)) { result.append(decodeEncode(protocol.toLowerCase())).append("://"); } if (!StringUtils.isEmpty(userInfo)) { result.append(decodeEncode(userInfo, ":")).append("@"); } if (!StringUtils.isEmpty(host)) { result.append(decodeEncode(host.toLowerCase())); } if (port != -1 && port != 80) { result.append(":").append(port); } if (!StringUtils.isEmpty(path)) { result.append(normalizePath(path)); } if (!StringUtils.isEmpty(query)) { String normalizedQuery = normalizeQueryString(uri); if (!StringUtils.isBlank(normalizedQuery)) { result.append("?").append(normalizedQuery); } } if (!StringUtils.isEmpty(reference)) { result.append("#").append(decodeEncode(reference)); } } catch (UnsupportedEncodingException e) { throw new CRRuntimeException("Unsupported encoding: " + e.getMessage(), e); } return result.toString(); }