List of usage examples for java.net URL getQuery
public String getQuery()
From source file:com.k42b3.neodym.oauth.Oauth.java
public boolean accessToken() throws Exception { // add values HashMap<String, String> values = new HashMap<String, String>(); String requestMethod = "GET"; values.put("oauth_consumer_key", this.provider.getConsumerKey()); values.put("oauth_token", this.token); values.put("oauth_signature_method", provider.getMethod()); values.put("oauth_timestamp", this.getTimestamp()); values.put("oauth_nonce", this.getNonce()); values.put("oauth_verifier", this.verificationCode); // add get vars to values URL accessUrl = new URL(provider.getAccessUrl()); values.putAll(parseQuery(accessUrl.getQuery())); // build base string String baseString = this.buildBaseString(requestMethod, provider.getAccessUrl(), values); // get signature SignatureInterface signature = this.getSignature(); if (signature == null) { throw new Exception("Invalid signature method"); }//ww w . j a v a 2 s .c o m // build signature values.put("oauth_signature", signature.build(baseString, provider.getConsumerSecret(), this.tokenSecret)); // add header to request HashMap<String, String> header = new HashMap<String, String>(); header.put("Authorization", "OAuth realm=\"neodym\", " + this.buildAuthString(values)); String responseContent = http.request(Http.GET, provider.getAccessUrl(), header); // parse response this.token = null; this.tokenSecret = null; HashMap<String, String> response = parseQuery(responseContent); Set<String> keys = response.keySet(); for (String key : keys) { if (key.equals("oauth_token")) { this.token = response.get(key); logger.info("Received token: " + this.token); } if (key.equals("oauth_token_secret")) { this.tokenSecret = response.get(key); logger.info("Received token secret: " + this.tokenSecret); } } if (this.token == null) { throw new Exception("No oauth token received"); } if (this.tokenSecret == null) { throw new Exception("No oauth token secret received"); } return true; }
From source file:wjhk.jupload2.upload.FileUploadThreadHTTP.java
/** @see DefaultFileUploadThread#startRequest(long, boolean, int, boolean) */ @Override//from ww w . j a v a2s. c om void startRequest(long contentLength, boolean bChunkEnabled, int chunkPart, boolean bLastChunk) throws JUploadException { try { String chunkHttpParam = "jupart=" + chunkPart + "&jufinal=" + (bLastChunk ? "1" : "0"); this.uploadPolicy.displayDebug("chunkHttpParam: " + chunkHttpParam, 30); URL url = new URL(this.uploadPolicy.getPostURL()); // Add the chunking query params to the URL if there are any if (bChunkEnabled) { if (null != url.getQuery() && !"".equals(url.getQuery())) { url = new URL(url.toExternalForm() + "&" + chunkHttpParam); } else { url = new URL(url.toExternalForm() + "?" + chunkHttpParam); } } this.connectionHelper.initRequest(url, "POST", bChunkEnabled, bLastChunk); // Get the GET parameters from the URL and convert them to // post form params ByteArrayEncoder formParams = getFormParamsForPostRequest(url); contentLength += formParams.getEncodedLength(); this.connectionHelper.append("Content-Type: multipart/form-data; boundary=") .append(this.connectionHelper.getBoundary().substring(2)).append("\r\n"); this.connectionHelper.append("Content-Length: ").append(String.valueOf(contentLength)).append("\r\n"); // Blank line (end of header) this.connectionHelper.append("\r\n"); // formParams are not really part of the main header, but we add // them here anyway. We write directly into the // ByteArrayOutputStream, as we already encoded them, to get the // encoded length. We need to flush the writer first, before // directly writing to the ByteArrayOutputStream. this.connectionHelper.append(formParams); // Let's call the server this.connectionHelper.sendRequest(); // Debug output: always called, so that the debug file is correctly // filled. this.uploadPolicy .displayDebug( "=== main header (len=" + this.connectionHelper.getByteArrayEncoder().getEncodedLength() + "):\n" + quoteCRLF(this.connectionHelper.getByteArrayEncoder().getString()), 70); this.uploadPolicy.displayDebug("=== main header end", 70); } catch (IOException e) { throw new JUploadIOException(e); } catch (IllegalArgumentException e) { throw new JUploadException(e); } }
From source file:com.k42b3.neodym.oauth.Oauth.java
public boolean requestToken() throws Exception { // add values HashMap<String, String> values = new HashMap<String, String>(); String requestMethod = "GET"; values.put("oauth_consumer_key", this.provider.getConsumerKey()); values.put("oauth_signature_method", provider.getMethod()); values.put("oauth_timestamp", this.getTimestamp()); values.put("oauth_nonce", this.getNonce()); values.put("oauth_version", this.getVersion()); values.put("oauth_callback", "oob"); // add get vars to values URL requestUrl = new URL(provider.getRequestUrl()); values.putAll(parseQuery(requestUrl.getQuery())); // build base string String baseString = this.buildBaseString(requestMethod, provider.getRequestUrl(), values); // get signature SignatureInterface signature = this.getSignature(); if (signature == null) { throw new Exception("Invalid signature method"); }//from ww w . ja v a 2s. c o m // build signature values.put("oauth_signature", signature.build(baseString, provider.getConsumerSecret(), "")); // add header to request HashMap<String, String> header = new HashMap<String, String>(); header.put("Authorization", "OAuth realm=\"neodym\", " + this.buildAuthString(values)); String responseContent = http.request(Http.GET, provider.getRequestUrl(), header); // parse response this.token = null; this.tokenSecret = null; this.callbackConfirmed = false; HashMap<String, String> response = parseQuery(responseContent); Set<String> keys = response.keySet(); for (String key : keys) { if (key.equals("oauth_token")) { this.token = response.get(key); logger.info("Received token: " + this.token); } if (key.equals("oauth_token_secret")) { this.tokenSecret = response.get(key); logger.info("Received token secret: " + this.tokenSecret); } if (key.equals("oauth_callback_confirmed")) { this.tokenSecret = response.get(key); this.callbackConfirmed = response.get(key).equals("1"); } } if (this.token == null) { throw new Exception("No oauth token received"); } if (this.tokenSecret == null) { throw new Exception("No oauth token secret received"); } if (this.callbackConfirmed != true) { throw new Exception("Callback was not confirmed"); } return true; }
From source file:org.apache.jmeter.protocol.amf.proxy.AmfProxy.java
private String getUrlWithoutQuery(URL url) { String fullUrl = url.toString(); String urlWithoutQuery = fullUrl; String query = url.getQuery(); if (query != null) { // Get rid of the query and the ? urlWithoutQuery = urlWithoutQuery.substring(0, urlWithoutQuery.length() - query.length() - 1); }/* w w w.j a v a 2 s .c o m*/ return urlWithoutQuery; }
From source file:org.pocketcampus.plugin.moodle.server.old.MoodleServiceImpl.java
public TequilaToken getTequilaTokenForMoodle() throws TException { System.out.println("getTequilaTokenForMoodle"); try {/*from www. j a v a2s . c o m*/ HttpURLConnection conn2 = (HttpURLConnection) new URL("http://moodle.epfl.ch/auth/tequila/index.php") .openConnection(); conn2.setInstanceFollowRedirects(false); conn2.getInputStream(); URL url = new URL(conn2.getHeaderField("Location")); MultiMap<String> params = new MultiMap<String>(); UrlEncoded.decodeTo(url.getQuery(), params, "UTF-8"); TequilaToken teqToken = new TequilaToken(params.getString("requestkey")); Cookie cookie = new Cookie(); for (String header : conn2.getHeaderFields().get("Set-Cookie")) { cookie.addFromHeader(header); } teqToken.setLoginCookie(cookie.cookie()); return teqToken; } catch (IOException e) { e.printStackTrace(); throw new TException("Failed to getTequilaToken from upstream server"); } }
From source file:com.adito.replacementproxy.ProxiedRequestDispatcher.java
/** * Send the request to the target server. * //w ww . ja v a 2 s . c o m * @return request successful * @throws Exception on any error */ public boolean sendProxiedRequest() throws Exception { byte[] content = null; OutputStream serverOut = null; HttpClient client; SessionClients clients = null; HttpSession session = requestProcessor.getSession(); // Manage the sessions clients synchronized (session) { clients = (SessionClients) session.getAttribute(Constants.HTTP_CLIENTS); if (clients == null) { clients = new SessionClients(); session.setAttribute(Constants.HTTP_CLIENTS, clients); } } RequestParameterMap requestParameters = requestProcessor.getRequestParameters(); URL proxiedURL = requestParameters.getProxiedURIDetails().getProxiedURL(); synchronized (clients) { String key = proxiedURL.getHost() + ":" + (proxiedURL.getPort() > 0 ? proxiedURL.getPort() : proxiedURL.getProtocol().equals("https") ? 443 : 80) + ":" + proxiedURL.getProtocol().equals("https") + ":" + requestProcessor.getWebForward().getResourceId() + Thread.currentThread().getName(); client = (HttpClient) clients.get(key); if (client == null) { client = new HttpClient(proxiedURL.getHost(), (proxiedURL.getPort() > 0 ? proxiedURL.getPort() : proxiedURL.getProtocol().equals("https") ? 443 : 80), proxiedURL.getProtocol().equals("https")); if (!requestProcessor.getWebForward().getPreferredAuthenticationScheme() .equals(HttpAuthenticatorFactory.NONE) && !requestProcessor.getWebForward().getAuthenticationUsername().equals("") && !requestProcessor.getWebForward().getAuthenticationPassword().equals("")) { PasswordCredentials pwd = new PasswordCredentials(); pwd.setUsername(SessionInfoReplacer.replace(requestProcessor.getSessionInfo(), requestProcessor.getWebForward().getAuthenticationUsername())); pwd.setPassword(SessionInfoReplacer.replace(requestProcessor.getSessionInfo(), requestProcessor.getWebForward().getAuthenticationPassword())); client.setCredentials(pwd); } // Set the preferred scheme client.setPreferredAuthentication( requestProcessor.getWebForward().getPreferredAuthenticationScheme()); // Do not track cookies, browser will instead client.setIncludeCookies(false); // If we're using basic authentication then preempt the 401 // response client.setPreemtiveAuthentication(requestProcessor.getWebForward() .getPreferredAuthenticationScheme().equalsIgnoreCase("BASIC")); clients.put(key, client); } } if (log.isDebugEnabled()) log.debug("Connecting to [" + proxiedURL + "] "); ProxiedHttpMethod method; if (!requestProcessor.getWebForward().getFormType().equals(WebForwardTypes.FORM_SUBMIT_NONE) && !requestProcessor.getWebForward().getFormType().equals("") && !requestProcessor.getWebForward().getFormType().equals(WebForwardTypes.FORM_SUBMIT_JAVASCRIPT) && !Boolean.TRUE.equals(launchSession.getAttribute(LAUNCH_ATTR_AUTH_POSTED))) { /** * This code will automatically submit form parameters. * * LDP - Use the full URI with parameters as we need to ensure parameters are sent as they are received. */ method = new ProxiedHttpMethod(requestProcessor.getWebForward().getFormType(), SessionInfoReplacer.replace(requestProcessor.getSessionInfo(), requestProcessor.getUriEncoded()), requestProcessor.getWebForward().getFormType().equals(WebForwardTypes.FORM_SUBMIT_POST) ? new MultiMap() : requestParameters, requestProcessor.getSessionInfo(), requestProcessor.getWebForward().getFormType().equals(WebForwardTypes.FORM_SUBMIT_POST)); if (requestProcessor.getWebForward().getEncoding() != null && !requestProcessor.getWebForward().getEncoding().equals(WebForwardTypes.DEFAULT_ENCODING)) method.setCharsetEncoding(requestProcessor.getWebForward().getEncoding()); StringTokenizer tokens = new StringTokenizer(requestProcessor.getWebForward().getFormParameters(), "\n"); int idx; String param; while (tokens.hasMoreTokens()) { param = SessionInfoReplacer.replace(requestProcessor.getLaunchSession().getSession(), tokens.nextToken().trim()); idx = param.indexOf('='); if (idx > -1 && idx < param.length() - 1) { method.addParameter(param.substring(0, idx), param.substring(idx + 1)); } else method.addParameter(param, ""); } launchSession.setAttribute(LAUNCH_ATTR_AUTH_POSTED, Boolean.TRUE); } else { /** * LDP - Use the full URI with parameters as we need to ensure parameters are sent as they are received. */ method = new ProxiedHttpMethod(requestProcessor.getMethod(), SessionInfoReplacer.replace(requestProcessor.getSessionInfo(), requestProcessor.getUriEncoded()), requestParameters, requestProcessor.getSessionInfo(), requestProcessor.getRequest().getContentType() != null && requestProcessor.getRequest() .getContentType().startsWith("application/x-www-form-urlencoded")); if (requestProcessor.getWebForward().getEncoding() != null && !requestProcessor.getWebForward().getEncoding().equals(WebForwardTypes.DEFAULT_ENCODING)) method.setCharsetEncoding(requestProcessor.getWebForward().getEncoding()); } int contentLength = 0; String contentType = null; for (Enumeration e = requestProcessor.getHeaderNames(); e.hasMoreElements();) { String hdr = (String) e.nextElement(); if (ignoreHeaders.containsKey(hdr)) { if (log.isDebugEnabled()) log.debug("Ignoring " + hdr + " = " + requestProcessor.getHeader(hdr)); continue; } // See if there any replacements for this header List replacements = WebForwardDatabaseFactory.getInstance().getReplacementsForContent( launchSession.getSession().getUser().getPrincipalName(), Replacement.REPLACEMENT_TYPE_SENT_HEADER, hdr, proxiedURL.toExternalForm()); Enumeration vals = requestProcessor.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); // Do the replacements for (Iterator i = replacements.iterator(); i.hasNext();) { Replacement r = (Replacement) i.next(); val = val.replaceAll(r.getMatchPattern(), r.getReplacePattern()); } if (val != null) { if (hdr.equalsIgnoreCase(HttpConstants.HDR_HOST)) { if (proxiedURL.getPort() == -1) { val = proxiedURL.getHost(); } else { val = proxiedURL.getHost() + ":" + proxiedURL.getPort(); } } else if (hdr.equalsIgnoreCase(HttpConstants.HDR_COOKIE)) { // We shouldnt supply our local cookies if (log.isDebugEnabled()) log.debug(" Splitting cookie " + val); String[] cookieVals = val.split("\\;"); StringBuffer newVal = new StringBuffer(); for (int i = 0; i < cookieVals.length; i++) { if (log.isDebugEnabled()) log.debug("Cookie = " + cookieVals[i]); int idx = cookieVals[i].indexOf('='); String cn = ""; String cv = ""; if (idx == -1) { cn = Util.trimBoth(cookieVals[i]); } else if (idx < cookieVals[i].length() - 1) { cn = Util.trimBoth(cookieVals[i].substring(0, idx)); cv = Util.trimBoth(cookieVals[i].substring(idx + 1)); } else { cn = Util.trimBoth(cookieVals[i].substring(0, idx)); } if (cn.equals("webForward") || cn.equals(Constants.LOGON_TICKET) || cn.equals(Constants.DOMAIN_LOGON_TICKET) || (cn.equals(sessionIdCookieName) && cv.equals(requestProcessor.getSession().getId()))) { if (log.isDebugEnabled()) log.debug(" Omiting cookie " + cn + "=" + cv); } else { // TODO is it ok to store the cookie map in // memory? CookieItem cookie = cookieMap.getByFakeCookieName(cn); if (cookie == null) { if (log.isDebugEnabled()) log.debug(" Cookie " + cn + " unmapped, ignoring"); // Un-mapped cookie, ignore } else { if (log.isDebugEnabled()) log.debug(" Including cookie " + cn + "=" + cv); if (newVal.length() > 0) { newVal.append("; "); } newVal.append(cookie.getRealCookieName()); newVal.append("="); newVal.append(Util.urlDecode(cv)); } } } if (newVal.length() == 0) { if (log.isDebugEnabled()) log.debug("Send no cookies"); val = null; } else { val = newVal.toString(); if (log.isDebugEnabled()) log.debug("Using cooking val of " + val); } } // Change the refererer else if (hdr.equalsIgnoreCase(HttpConstants.HDR_REFERER)) { try { URL refUrl = new URL(val); refUrl.getQuery(); if (log.isDebugEnabled()) log.debug("Splitting refererer query string [" + val + "] " + refUrl.getQuery()); if (refUrl.getFile() != null) { ProxyURIDetails uriDetails = RequestParameterMap.parseProxyPath(refUrl.getFile(), "UTF-8"); if (uriDetails.getProxiedURL() == null) { /* If the referer is not a proxied URL then don't send a referer. This * way a target server won't know its a request from Adito by * examining the referer */ val = null; } else { val = uriDetails.getProxiedURL().toExternalForm(); } } } catch (MalformedURLException murle) { } } else if (hdr.equalsIgnoreCase(HttpConstants.HDR_CONTENT_LENGTH)) { contentLength = Integer.parseInt(val); continue; } else if (hdr.equalsIgnoreCase(HttpConstants.HDR_CONTENT_TYPE)) { contentType = val; continue; } else if (hdr.equalsIgnoreCase(HttpConstants.HDR_CONNECTION)) { // Handled by the Maverick HTTP client continue; } if (val != null) { method.getProxiedRequest().addHeaderField(hdr, val); } if (log.isDebugEnabled()) log.debug("Adding request property " + hdr + " = " + val); } } } // Proxy headers method.getProxiedRequest().setHeaderField("Via", Branding.PRODUCT_NAME); if (requestParameters.isMultipart() && requestParameters.getMultipartDataLength() > 0) { method.setContent(getDebugStream(requestParameters.getMultipartData()), requestParameters.getMultipartDataLength(), requestParameters.getOriginalContentType()); } else if (!requestParameters.isWwwFormURLEncoded() && contentLength > 0) { method.setContent(getDebugStream(requestProcessor.getRequest().getInputStream()), requestParameters.getOriginalContentLength(), requestParameters.getOriginalContentType()); } serverResponse = client.execute(method); responseCode = serverResponse.getStatus(); responseMessage = serverResponse.getReason(); return true; }
From source file:com.gargoylesoftware.htmlunit.WebRequest.java
/** * Sets the target URL. The URL may be simplified if needed (for instance eliminating * irrelevant path portions like "/./"). * @param url the target URL/* w w w . j a v a 2 s .co m*/ */ public void setUrl(URL url) { if (url != null) { final String path = url.getPath(); if (path.isEmpty()) { url = buildUrlWithNewFile(url, "/" + url.getFile()); } else if (path.contains("/.")) { final String query = (url.getQuery() != null) ? "?" + url.getQuery() : ""; url = buildUrlWithNewFile(url, removeDots(path) + query); } url_ = url.toExternalForm(); // http://john.smith:secret@localhost final String userInfo = url.getUserInfo(); if (userInfo != null) { final int splitPos = userInfo.indexOf(':'); if (splitPos == -1) { urlCredentials_ = new UsernamePasswordCredentials(userInfo, ""); } else { final String username = userInfo.substring(0, splitPos); final String password = userInfo.substring(splitPos + 1); urlCredentials_ = new UsernamePasswordCredentials(username, password); } } } else { url_ = null; } }
From source file:jeeves.utils.XmlRequest.java
public XmlRequest(URL url) { this(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort(), url.getProtocol()); address = url.getPath();/*from w w w . ja v a2s .c om*/ query = url.getQuery(); }
From source file:org.chiba.connectors.smtp.SMTPSubmissionHandler.java
private void send(String uri, byte[] data, String encoding, String mediatype) throws Exception { URL url = new URL(uri); String recipient = url.getPath(); String server = null;//from www . java2s. c om String port = null; String sender = null; String subject = null; String username = null; String password = null; StringTokenizer headers = new StringTokenizer(url.getQuery(), "&"); while (headers.hasMoreTokens()) { String token = headers.nextToken(); if (token.startsWith("server=")) { server = URLDecoder.decode(token.substring("server=".length())); continue; } if (token.startsWith("port=")) { port = URLDecoder.decode(token.substring("port=".length())); continue; } if (token.startsWith("sender=")) { sender = URLDecoder.decode(token.substring("sender=".length())); continue; } if (token.startsWith("subject=")) { subject = URLDecoder.decode(token.substring("subject=".length())); continue; } if (token.startsWith("username=")) { username = URLDecoder.decode(token.substring("username=".length())); continue; } if (token.startsWith("password=")) { password = URLDecoder.decode(token.substring("password=".length())); continue; } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("smtp server '" + server + "'"); if (username != null) { LOGGER.debug("smtp-auth username '" + username + "'"); } LOGGER.debug("mail sender '" + sender + "'"); LOGGER.debug("subject line '" + subject + "'"); } Properties properties = System.getProperties(); properties.put("mail.debug", String.valueOf(LOGGER.isDebugEnabled())); properties.put("mail.smtp.from", sender); properties.put("mail.smtp.host", server); if (port != null) { properties.put("mail.smtp.port", port); } if (username != null) { properties.put("mail.smtp.auth", String.valueOf(true)); properties.put("mail.smtp.user", username); } Session session = Session.getInstance(properties, new SMTPAuthenticator(username, password)); MimeMessage message = null; if (mediatype.startsWith("multipart/")) { message = new MimeMessage(session, new ByteArrayInputStream(data)); } else { message = new MimeMessage(session); if (mediatype.toLowerCase().indexOf("charset=") == -1) { mediatype += "; charset=\"" + encoding + "\""; } message.setText(new String(data, encoding), encoding); message.setHeader("Content-Type", mediatype); } message.setRecipient(RecipientType.TO, new InternetAddress(recipient)); message.setSubject(subject); message.setSentDate(new Date()); Transport.send(message); }