List of usage examples for org.apache.commons.httpclient HttpClient getParams
public HttpClientParams getParams()
From source file:es.uvigo.ei.sing.jarvest.core.HTTPUtils.java
public synchronized static InputStream doPost(String urlstring, String queryString, String separator, Map<String, String> additionalHeaders, StringBuffer charsetb) throws HttpException, IOException { System.err.println("posting to: " + urlstring + ". query string: " + queryString); HashMap<String, String> query = parseQueryString(queryString, separator); HttpClient client = getClient(); URL url = new URL(urlstring); int port = url.getPort(); if (port == -1) { if (url.getProtocol().equalsIgnoreCase("http")) { port = 80;//ww w. j a v a2s . com } if (url.getProtocol().equalsIgnoreCase("https")) { port = 443; } } client.getHostConfiguration().setHost(url.getHost(), port, url.getProtocol()); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); final PostMethod post = new PostMethod(url.getFile()); addHeaders(additionalHeaders, post); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); post.setRequestHeader("Accept", "*/*"); // Prepare login parameters NameValuePair[] valuePairs = new NameValuePair[query.size()]; int counter = 0; for (String key : query.keySet()) { //System.out.println("Adding pair: "+key+": "+query.get(key)); valuePairs[counter++] = new NameValuePair(key, query.get(key)); } post.setRequestBody(valuePairs); //authpost.setRequestEntity(new StringRequestEntity(requestEntity)); client.executeMethod(post); int statuscode = post.getStatusCode(); InputStream toret = null; if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header header = post.getResponseHeader("location"); if (header != null) { String newuri = header.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } } else { System.out.println("Invalid redirect"); System.exit(1); } } else { charsetb.append(post.getResponseCharSet()); final InputStream in = post.getResponseBodyAsStream(); toret = new InputStream() { @Override public int read() throws IOException { return in.read(); } @Override public void close() { post.releaseConnection(); } }; } return toret; }
From source file:com.eucalyptus.webui.server.ConfigurationWebBackend.java
private static String getExternalIpAddress() { String ipAddr = null;// w w w.j a va 2 s . c o m HttpClient httpClient = new HttpClient(); //set User-Agent String clientVersion = (String) httpClient.getParams().getDefaults() .getParameter(HttpMethodParams.USER_AGENT); String javaVersion = System.getProperty("java.version"); String osName = System.getProperty("os.name"); String osArch = System.getProperty("os.arch"); String eucaVersion = System.getProperty("euca.version"); String extraVersion = System.getProperty("euca.extra_version"); // Jakarta Commons-HttpClient/3.1 (java 1.6.0_24; Linux amd64) Eucalyptus/3.1.0-1.el6 String userAgent = clientVersion + " (java " + javaVersion + "; " + osName + " " + osArch + ") Eucalyptus/" + eucaVersion; if (extraVersion != null) { userAgent = userAgent + "-" + extraVersion; } httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent); //support for http proxy if (HttpServerBootstrapper.httpProxyHost != null && (HttpServerBootstrapper.httpProxyHost.length() > 0)) { String proxyHost = HttpServerBootstrapper.httpProxyHost; if (HttpServerBootstrapper.httpProxyPort != null && (HttpServerBootstrapper.httpProxyPort.length() > 0)) { int proxyPort = Integer.parseInt(HttpServerBootstrapper.httpProxyPort); httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort); } else { httpClient.getHostConfiguration().setProxyHost(new ProxyHost(proxyHost)); } } // Use Rightscale's "whoami" service String whoamiUrl = WebProperties.getProperty(WebProperties.RIGHTSCALE_WHOAMI_URL, WebProperties.RIGHTSCALE_WHOAMI_URL_DEFAULT); GetMethod method = new GetMethod(whoamiUrl); Integer timeoutMs = new Integer(3 * 1000); // TODO: is this working? method.getParams().setSoTimeout(timeoutMs); try { httpClient.executeMethod(method); String str = ""; InputStream in = method.getResponseBodyAsStream(); byte[] readBytes = new byte[1024]; int bytesRead = -1; while ((bytesRead = in.read(readBytes)) > 0) { str += new String(readBytes, 0, bytesRead); } Matcher matcher = Pattern.compile(".*your ip is (.*)").matcher(str); if (matcher.find()) { ipAddr = matcher.group(1); } } catch (MalformedURLException e) { LOG.warn("Malformed URL exception: " + e.getMessage()); LOG.debug(e, e); } catch (IOException e) { LOG.warn("I/O exception: " + e.getMessage()); LOG.debug(e, e); } finally { method.releaseConnection(); } return ipAddr; }
From source file:de.mpg.mpdl.inge.transformation.Util.java
/** * Queries CoNE service and returns the result as DOM node. The returned XML has the following * structure: <cone> <author> <familyname>Buxtehude-Mlln</familyname> * <givenname>Heribert</givenname> <prefix>von und zu</prefix> <title>Knig</title> </author> * <author> <familyname>Mller</familyname> <givenname>Peter</givenname> </author> </authors> * // www . j a v a2s . c om * @param authors * @return */ public static Node queryCone(String model, String query) { DocumentBuilder documentBuilder; String queryUrl = null; try { logger.info("queryCone: " + model + " query: " + query); documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("cone"); document.appendChild(element); queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&q=" + URLEncoder.encode(query, "UTF-8"); String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/resource/$1?format=rdf"; HttpClient client = new HttpClient(); client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); GetMethod method = new GetMethod(queryUrl); String coneSession = getConeSession(); if (coneSession != null) { method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession); } ProxyHelper.executeMethod(client, method); if (method.getStatusCode() == 200) { String[] results = method.getResponseBodyAsString().split("\n"); for (String result : results) { if (!"".equals(result.trim())) { String id = result.split("\\|")[1]; // TODO "&redirect=true" must be reinserted again GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle=" + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8"))); detailMethod.setFollowRedirects(true); if (coneSession != null) { detailMethod.setRequestHeader("Cookie", "JSESSIONID=" + coneSession); } ProxyHelper.executeMethod(client, detailMethod); logger.info("CoNE query: " + id + "?format=rdf&eSciDocUserHandle=" + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")) + " returned " + detailMethod.getResponseBodyAsString()); if (detailMethod.getStatusCode() == 200) { Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream()); element.appendChild(document.importNode(details.getFirstChild(), true)); } else { logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n" + detailMethod.getResponseBodyAsString()); } } } } else { logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n" + method.getResponseBodyAsString()); } return document; } catch (Exception e) { logger.error("Error querying CoNE service. This is normal during unit tests. (" + queryUrl + ") .Otherwise it should be clarified if any measures have to be taken.", e); logger.debug("Stacktrace", e); return null; // throw new RuntimeException(e); } }
From source file:de.mpg.mpdl.inge.transformation.Util.java
/** * Queries the CoNE service and transforms the result into a DOM node. * /* ww w. j a v a 2 s. co m*/ * @param model The type of object (e.g. "persons") * @param name The query string. * @param ou Specialty for persons * @param coneSession A JSESSIONID to not produce a new session with each call. * @return A DOM node containing the results. */ public static Node queryConeExactWithIdentifier(String model, String identifier, String ou) { DocumentBuilder documentBuilder; try { logger.info("queryConeExactWithIdentifier: " + model + " identifier: " + identifier + " ou: " + ou); documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("cone"); document.appendChild(element); String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&dc:identifier/" + URLEncoder.encode("rdf:value", "UTF-8") + "=" + URLEncoder.encode("\"" + identifier + "\"", "UTF-8") + "&" + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "=" + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8"); String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/resource/$1?format=rdf"; HttpClient client = new HttpClient(); client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); GetMethod method = new GetMethod(queryUrl); String coneSession = getConeSession(); if (coneSession != null) { method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession); } ProxyHelper.executeMethod(client, method); logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString()); if (method.getStatusCode() == 200) { ArrayList<String> results = new ArrayList<String>(); results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n"))); Set<String> oldIds = new HashSet<String>(); for (String result : results) { if (!"".equals(result.trim())) { String id = result.split("\\|")[1]; if (!oldIds.contains(id)) { // TODO "&redirect=true" must be reinserted again GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle=" + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8"))); detailMethod.setFollowRedirects(true); ProxyHelper.setProxy(client, detailsUrl.replace("$1", id)); client.executeMethod(detailMethod); // TODO "&redirect=true" must be reinserted again logger.info("CoNE query: " + id + "?format=rdf&eSciDocUserHandle=" + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")) + " returned " + detailMethod.getResponseBodyAsString()); if (detailMethod.getStatusCode() == 200) { Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream()); element.appendChild(document.importNode(details.getFirstChild(), true)); } else { logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n" + detailMethod.getResponseBodyAsString()); } oldIds.add(id); } } } } else { logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n" + method.getResponseBodyAsString()); } return document; } catch (Exception e) { logger.error("Error querying CoNE service. This is normal during unit tests. " + "Otherwise it should be clarified if any measures have to be taken.", e); return null; // throw new RuntimeException(e); } }
From source file:de.mpg.mpdl.inge.transformation.Util.java
/** * Queries the CoNE service and transforms the result into a DOM node. * //from www . j a v a2s . co m * @param model The type of object (e.g. "persons") * @param name The query string. * @param ou Specialty for persons * @param coneSession A JSESSIONID to not produce a new session with each call. * @return A DOM node containing the results. */ public static Node queryConeExact(String model, String name, String ou) { DocumentBuilder documentBuilder; try { logger.info("queryConeExact: " + model + " name: " + name + " ou: " + ou); documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("cone"); document.appendChild(element); String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&" + URLEncoder.encode("dc:title", "UTF-8") + "=" + URLEncoder.encode("\"" + name + "\"", "UTF-8") + "&" + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "=" + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8"); String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/resource/$1?format=rdf"; HttpClient client = new HttpClient(); client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); GetMethod method = new GetMethod(queryUrl); String coneSession = getConeSession(); if (coneSession != null) { method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession); } ProxyHelper.executeMethod(client, method); logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString()); if (method.getStatusCode() == 200) { ArrayList<String> results = new ArrayList<String>(); results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n"))); queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&" + URLEncoder.encode("dcterms:alternative", "UTF-8") + "=" + URLEncoder.encode("\"" + name + "\"", "UTF-8") + "&" + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "=" + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8"); client = new HttpClient(); method = new GetMethod(queryUrl); if (coneSession != null) { method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession); } ProxyHelper.executeMethod(client, method); logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString()); if (method.getStatusCode() == 200) { results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n"))); Set<String> oldIds = new HashSet<String>(); for (String result : results) { if (!"".equals(result.trim())) { String id = result.split("\\|")[1]; if (!oldIds.contains(id)) { // TODO "&redirect=true" must be reinserted again GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle=" + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8"))); detailMethod.setFollowRedirects(true); ProxyHelper.setProxy(client, detailsUrl.replace("$1", id)); client.executeMethod(detailMethod); // TODO "&redirect=true" must be reinserted again logger.info("CoNE query: " + id + "?format=rdf&eSciDocUserHandle=" + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")) + " returned " + detailMethod.getResponseBodyAsString()); if (detailMethod.getStatusCode() == 200) { Document details = documentBuilder .parse(detailMethod.getResponseBodyAsStream()); element.appendChild(document.importNode(details.getFirstChild(), true)); } else { logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n" + detailMethod.getResponseBodyAsString()); } oldIds.add(id); } } } } } else { logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n" + method.getResponseBodyAsString()); } return document; } catch (Exception e) { logger.error("Error querying CoNE service. This is normal during unit tests. " + "Otherwise it should be clarified if any measures have to be taken.", e); return null; // throw new RuntimeException(e); } }
From source file:cn.edu.seu.herald.ws.api.impl.ServiceRequesterFactory.java
HttpClient newServiceRequester() { HttpClient serviceRequester = new HttpClient(); serviceRequester.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); return serviceRequester; }
From source file:eu.learnpad.rest.utils.RestResource.java
public HttpClient getClient(String userName, String password) { HttpClient httpClient = new HttpClient(); httpClient.getParams().setAuthenticationPreemptive(true); Credentials credentials = new UsernamePasswordCredentials(userName, password); AuthScope authentication = new AuthScope(this.HOSTNAME, this.PORT, AuthScope.ANY_REALM); httpClient.getState().setCredentials(authentication, credentials); return httpClient; }
From source file:com.braindrainpain.docker.HttpSupport.java
protected HttpClient getHttpClient() { HttpClient client = new HttpClient(); client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, this.getSystemProperty("docker.repo.connection.timeout", 10 * 1000)); client.getParams().setSoTimeout(this.getSystemProperty("docker.repo.socket.timeout", 5 * 60 * 1000)); return client; }
From source file:com.tw.go.plugin.material.artifactrepository.yum.exec.HttpConnectionChecker.java
HttpClient getHttpClient() { HttpClient client = new HttpClient(); client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, getSystemProperty("yum.repo.connection.timeout", 10 * 1000)); client.getParams().setSoTimeout(getSystemProperty("yum.repo.socket.timeout", 5 * 60 * 1000)); return client; }
From source file:com.sun.syndication.propono.atom.client.BasicAuthStrategy.java
public void addAuthentication(HttpClient httpClient, HttpMethodBase method) throws ProponoException { httpClient.getParams().setAuthenticationPreemptive(true); String header = "Basic " + credentials; method.setRequestHeader("Authorization", header); }