List of usage examples for java.net URL getUserInfo
public String getUserInfo()
From source file:de.fhg.iais.asc.xslt.binaries.download.Downloader.java
private static URI createURI(URL url) throws URISyntaxException { return new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); }
From source file:com.github.rnewson.couchdb.lucene.HttpClientFactory.java
public static synchronized HttpClient getInstance() throws MalformedURLException { if (instance == null) { final HttpParams params = new BasicHttpParams(); // protocol params. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setUseExpectContinue(params, false); // connection params. HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setStaleCheckingEnabled(params, false); ConnManagerParams.setMaxTotalConnections(params, 1000); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1000)); final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 5984)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); final ClientConnectionManager cm = new ShieldedClientConnManager( new ThreadSafeClientConnManager(params, schemeRegistry)); instance = new DefaultHttpClient(cm, params); if (INI != null) { final CredentialsProvider credsProvider = new BasicCredentialsProvider(); final Iterator<?> it = INI.getKeys(); while (it.hasNext()) { final String key = (String) it.next(); if (!key.startsWith("lucene.") && key.endsWith(".url")) { final URL url = new URL(INI.getString(key)); if (url.getUserInfo() != null) { credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(url.getUserInfo())); }//from www .j a v a 2 s . co m } } instance.setCredentialsProvider(credsProvider); instance.addRequestInterceptor(new PreemptiveAuthenticationRequestInterceptor(), 0); } } return instance; }
From source file:org.motechproject.mmnaija.web.util.HTTPCommunicator.java
public static String doPost(String serviceUrl, String queryString) { URLConnection connection = null; try {//from w w w.j av a2s . c o m URL url = new URL(serviceUrl); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); url = uri.toURL(); // Open the connection connection = url.openConnection(); connection.setDoInput(true); connection.setUseCaches(false); // Disable caching the document connection.setDoOutput(true); // Triggers POST. connection.setRequestProperty("Content-Type", "text/html"); OutputStreamWriter writer = null; log.info("About to write"); try { if (null != connection.getOutputStream()) { writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(queryString); // Write POST query } else { log.warn("connection Null"); } // string. } catch (ConnectException ex) { log.warn("Exception : " + ex); // ex.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (Exception lg) { log.warn("Exception lg: " + lg.toString()); //lg.printStackTrace(); } } } InputStream in = connection.getInputStream(); // StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "utf-8"); String theString = writer.toString(); return theString; } catch (Exception e) { //e.printStackTrace(); log.warn("Error URL " + e.toString()); return ""; } }
From source file:org.commonjava.redhat.maven.rv.util.InputUtils.java
public static File getFile(final String location, final File downloadsDir, final boolean deleteExisting) throws ValidationException { if (client == null) { final DefaultHttpClient hc = new DefaultHttpClient(); hc.setRedirectStrategy(new DefaultRedirectStrategy()); final String proxyHost = System.getProperty("http.proxyHost"); final int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort", "-1")); if (proxyHost != null && proxyPort > 0) { final HttpHost proxy = new HttpHost(proxyHost, proxyPort); hc.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); }/* w w w . j a v a 2 s. co m*/ client = hc; } File result = null; if (location.startsWith("http")) { LOGGER.info("Downloading: '" + location + "'..."); try { final URL url = new URL(location); final String userpass = url.getUserInfo(); if (!isEmpty(userpass)) { final AuthScope scope = new AuthScope(url.getHost(), url.getPort()); final Credentials creds = new UsernamePasswordCredentials(userpass); client.getCredentialsProvider().setCredentials(scope, creds); } } catch (final MalformedURLException e) { LOGGER.error("Malformed URL: '" + location + "'", e); throw new ValidationException("Failed to download: %s. Reason: %s", e, location, e.getMessage()); } final File downloaded = new File(downloadsDir, new File(location).getName()); if (deleteExisting && downloaded.exists()) { downloaded.delete(); } if (!downloaded.exists()) { HttpGet get = new HttpGet(location); OutputStream out = null; try { HttpResponse response = client.execute(get); // Work around for scenario where we are loading from a server // that does a refresh e.g. gitweb if (response.containsHeader("Cache-control")) { LOGGER.info("Waiting for server to generate cache..."); try { Thread.sleep(5000); } catch (final InterruptedException e) { } get.abort(); get = new HttpGet(location); response = client.execute(get); } final int code = response.getStatusLine().getStatusCode(); if (code == 200) { final InputStream in = response.getEntity().getContent(); out = new FileOutputStream(downloaded); copy(in, out); } else { LOGGER.info(String.format("Received status: '%s' while downloading: %s", response.getStatusLine(), location)); throw new ValidationException("Received status: '%s' while downloading: %s", response.getStatusLine(), location); } } catch (final ClientProtocolException e) { throw new ValidationException("Failed to download: '%s'. Error: %s", e, location, e.getMessage()); } catch (final IOException e) { throw new ValidationException("Failed to download: '%s'. Error: %s", e, location, e.getMessage()); } finally { closeQuietly(out); get.abort(); } } result = downloaded; } else { LOGGER.info("Using local file: '" + location + "'..."); result = new File(location); } return result; }
From source file:Urls.java
public static String getNoRefForm(URL url) { String host = url.getHost();//from w w w.j a va 2 s. c om int port = url.getPort(); String portText = port == -1 ? "" : ":" + port; String userInfo = url.getUserInfo(); String userInfoText = userInfo == null || userInfo.length() == 0 ? "" : userInfo + "@"; String hostPort = host == null || host.length() == 0 ? "" : "//" + userInfoText + host + portText; return url.getProtocol() + ":" + hostPort + url.getFile(); }
From source file:com.seajas.search.utilities.tags.URLTag.java
/** * Protect a given URL by starring out the password-portion. * /*from www . j a v a 2s . c o m*/ * @param url * @return String */ public static String protectUrl(final String url) { try { URL actualUrl = new URL(url); return actualUrl.getProtocol() + "://" + (StringUtils.isEmpty(actualUrl.getUserInfo()) ? "" : "****@") + actualUrl.getHost() + (actualUrl.getPort() == -1 ? "" : ':' + actualUrl.getPort()) + actualUrl.getPath() + (StringUtils.isEmpty(actualUrl.getQuery()) ? "" : '?' + actualUrl.getQuery()); } catch (MalformedURLException e) { return url; } }
From source file:org.apache.jmeter.protocol.http.util.ConversionUtils.java
/** * @param url String Url to escape//from w w w.j a v a2 s. c o m * @return String cleaned up url * @throws Exception when given <code>url</code> leads to a malformed URL or URI */ public static String escapeIllegalURLCharacters(String url) throws Exception { String decodeUrl = URLDecoder.decode(url, "UTF-8"); URL urlString = new URL(decodeUrl); URI uri = new URI(urlString.getProtocol(), urlString.getUserInfo(), urlString.getHost(), urlString.getPort(), urlString.getPath(), urlString.getQuery(), urlString.getRef()); return uri.toString(); }
From source file:com.mashape.unirest.android.http.HttpClientHelper.java
private static HttpRequestBase prepareRequest(HttpRequest request, boolean async) { Object defaultHeaders = Options.getOption(Option.DEFAULT_HEADERS); if (defaultHeaders != null) { @SuppressWarnings("unchecked") Set<Entry<String, String>> entrySet = ((Map<String, String>) defaultHeaders).entrySet(); for (Entry<String, String> entry : entrySet) { request.header(entry.getKey(), entry.getValue()); }/*from ww w . j a v a 2s. com*/ } if (!request.getHeaders().containsKey(USER_AGENT_HEADER)) { request.header(USER_AGENT_HEADER, USER_AGENT); } if (!request.getHeaders().containsKey(ACCEPT_ENCODING_HEADER)) { request.header(ACCEPT_ENCODING_HEADER, "gzip"); } HttpRequestBase reqObj = null; String urlToRequest = null; try { URL url = new URL(request.getUrl()); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), URLDecoder.decode(url.getPath(), "UTF-8"), "", url.getRef()); urlToRequest = uri.toURL().toString(); if (url.getQuery() != null && !url.getQuery().trim().equals("")) { if (!urlToRequest.substring(urlToRequest.length() - 1).equals("?")) { urlToRequest += "?"; } urlToRequest += url.getQuery(); } else if (urlToRequest.substring(urlToRequest.length() - 1).equals("?")) { urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1); } } catch (Exception e) { throw new RuntimeException(e); } switch (request.getHttpMethod()) { case GET: reqObj = new HttpGet(urlToRequest); break; case POST: reqObj = new HttpPost(urlToRequest); break; case PUT: reqObj = new HttpPut(urlToRequest); break; case DELETE: //reqObj = new HttpDeleteWithBody(urlToRequest); break; case PATCH: //reqObj = new HttpPatchWithBody(urlToRequest); break; case OPTIONS: reqObj = new HttpOptions(urlToRequest); break; case HEAD: reqObj = new HttpHead(urlToRequest); break; } Set<Entry<String, List<String>>> entrySet = request.getHeaders().entrySet(); for (Entry<String, List<String>> entry : entrySet) { List<String> values = entry.getValue(); if (values != null) { for (String value : values) { reqObj.addHeader(entry.getKey(), value); } } } // Set body if (!(request.getHttpMethod() == HttpMethod.GET || request.getHttpMethod() == HttpMethod.HEAD)) { if (request.getBody() != null) { HttpEntity entity = request.getBody().getEntity(); if (async) { if (reqObj.getHeaders(CONTENT_TYPE) == null || reqObj.getHeaders(CONTENT_TYPE).length == 0) { reqObj.setHeader(entity.getContentType()); } try { ByteArrayOutputStream output = new ByteArrayOutputStream(); entity.writeTo(output); NByteArrayEntity en = new NByteArrayEntity(output.toByteArray()); ((HttpEntityEnclosingRequestBase) reqObj).setEntity(en); } catch (IOException e) { throw new RuntimeException(e); } } else { ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity); } } } return reqObj; }
From source file:com.bourke.kitchentimer.utils.Utils.java
public static void notifyServer(final String serverUrl) { new Thread(new Runnable() { @Override/*from w w w .j av a2 s . c om*/ public void run() { try { Log.d("Utils", "notifyServer:" + serverUrl); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(serverUrl); URL url = new URL(serverUrl); String userInfo = url.getUserInfo(); if (userInfo != null) { httpget.addHeader("Authorization", "Basic " + Base64.encodeToString(userInfo.getBytes(), Base64.NO_WRAP)); } HttpResponse response = httpclient.execute(httpget); response.getEntity().getContent().close(); httpclient.getConnectionManager().shutdown(); int status = response.getStatusLine().getStatusCode(); if (status < 200 || status > 299) { throw new Exception(response.getStatusLine().toString()); } } catch (Exception ex) { Log.e("Utils", "Error notifying server: ", ex); } } }).start(); }
From source file:eu.trentorise.smartcampus.protocolcarrier.Communicator.java
private static HttpRequestBase buildRequest(MessageRequest msgRequest, String appToken, String authToken) throws URISyntaxException, UnsupportedEncodingException { String host = msgRequest.getTargetHost(); if (host == null) throw new URISyntaxException(host, "null URI"); if (!host.endsWith("/")) host += '/'; String address = msgRequest.getTargetAddress(); if (address == null) address = ""; if (address.startsWith("/")) address = address.substring(1);/*from w w w . ja va 2 s .c o m*/ String uriString = host + address; try { URL url = new URL(uriString); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); uriString = uri.toURL().toString(); } catch (MalformedURLException e) { throw new URISyntaxException(uriString, e.getMessage()); } if (msgRequest.getQuery() != null) uriString += "?" + msgRequest.getQuery(); // new URI(uriString); HttpRequestBase request = null; if (msgRequest.getMethod().equals(Method.POST)) { HttpPost post = new HttpPost(uriString); HttpEntity httpEntity = null; if (msgRequest.getRequestParams() != null) { // if body and requestparams are either not null there is an // exception if (msgRequest.getBody() != null && msgRequest != null) { throw new IllegalArgumentException("body and requestParams cannot be either populated"); } httpEntity = new MultipartEntity(); for (RequestParam param : msgRequest.getRequestParams()) { if (param.getParamName() == null || param.getParamName().trim().length() == 0) { throw new IllegalArgumentException("paramName cannot be null or empty"); } if (param instanceof FileRequestParam) { FileRequestParam fileparam = (FileRequestParam) param; ((MultipartEntity) httpEntity).addPart(param.getParamName(), new ByteArrayBody( fileparam.getContent(), fileparam.getContentType(), fileparam.getFilename())); } if (param instanceof ObjectRequestParam) { ObjectRequestParam objectparam = (ObjectRequestParam) param; ((MultipartEntity) httpEntity).addPart(param.getParamName(), new StringBody(convertObject(objectparam.getVars()))); } } // mpe.addPart("file", // new ByteArrayBody(msgRequest.getFileContent(), "")); // post.setEntity(mpe); } if (msgRequest.getBody() != null) { httpEntity = new StringEntity(msgRequest.getBody(), Constants.CHARSET); ((StringEntity) httpEntity).setContentType(msgRequest.getContentType()); } post.setEntity(httpEntity); request = post; } else if (msgRequest.getMethod().equals(Method.PUT)) { HttpPut put = new HttpPut(uriString); if (msgRequest.getBody() != null) { StringEntity se = new StringEntity(msgRequest.getBody(), Constants.CHARSET); se.setContentType(msgRequest.getContentType()); put.setEntity(se); } request = put; } else if (msgRequest.getMethod().equals(Method.DELETE)) { request = new HttpDelete(uriString); } else { // default: GET request = new HttpGet(uriString); } Map<String, String> headers = new HashMap<String, String>(); // default headers if (appToken != null) { headers.put(RequestHeader.APP_TOKEN.toString(), appToken); } if (authToken != null) { // is here for compatibility headers.put(RequestHeader.AUTH_TOKEN.toString(), authToken); headers.put(RequestHeader.AUTHORIZATION.toString(), "Bearer " + authToken); } headers.put(RequestHeader.ACCEPT.toString(), msgRequest.getContentType()); if (msgRequest.getCustomHeaders() != null) { headers.putAll(msgRequest.getCustomHeaders()); } for (String key : headers.keySet()) { request.addHeader(key, headers.get(key)); } return request; }