List of usage examples for org.apache.commons.httpclient HttpClient getHttpConnectionManager
public HttpConnectionManager getHttpConnectionManager()
From source file:com.day.cq.wcm.foundation.impl.Rewriter.java
/** * Process a page.//from www. j ava 2 s . c o m */ public void rewrite(HttpServletRequest request, HttpServletResponse response) throws IOException { try { targetURL = new URI(target); } catch (URISyntaxException e) { IOException ioe = new IOException("Bad URI syntax: " + target); ioe.initCause(e); throw ioe; } setHostPrefix(targetURL); HttpClient httpClient = new HttpClient(); HttpState httpState = new HttpState(); HostConfiguration hostConfig = new HostConfiguration(); HttpMethodBase httpMethod; // define host hostConfig.setHost(targetURL.getHost(), targetURL.getPort()); // create http method String method = (String) request.getAttribute("cq.ext.app.method"); if (method == null) { method = request.getMethod(); } method = method.toUpperCase(); boolean isPost = "POST".equals(method); String urlString = targetURL.getPath(); StringBuffer query = new StringBuffer(); if (targetURL.getQuery() != null) { query.append("?"); query.append(targetURL.getQuery()); } //------------ GET --------------- if ("GET".equals(method)) { // add internal props Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); if (query.length() == 0) { query.append("?"); } else { query.append("&"); } query.append(Text.escape(name)); query.append("="); query.append(Text.escape(value)); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (query.length() == 0) { query.append("?"); } else { query.append("&"); } query.append(Text.escape(name)); query.append("="); query.append(Text.escape(values[i])); } } } httpMethod = new GetMethod(urlString + query); //------------ POST --------------- } else if ("POST".equals(method)) { PostMethod m = new PostMethod(urlString + query); httpMethod = m; String contentType = request.getContentType(); boolean mp = contentType != null && contentType.toLowerCase().startsWith("multipart/"); if (mp) { //------------ MULTPART POST --------------- List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); parts.add(new StringPart(name, value)); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration<String> e = request.getParameterNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { parts.add(new StringPart(name, values[i])); } } } m.setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), m.getParams())); } else { //------------ NORMAL POST --------------- // add internal props Iterator<String> iter = extraParams.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); String value = extraParams.get(name); m.addParameter(name, value); } if (passInput) { // add request params @SuppressWarnings("unchecked") Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); if (targetParamName.equals(name)) { continue; } String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { m.addParameter(name, values[i]); } } } } } else { log.error("Unsupported method ''{0}''", method); throw new IOException("Unsupported http method " + method); } log.debug("created http connection for method {0} to {1}", method, urlString + query); // add some request headers httpMethod.addRequestHeader("User-Agent", request.getHeader("User-Agent")); httpMethod.setFollowRedirects(!isPost); httpMethod.getParams().setSoTimeout(soTimeout); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); // send request httpClient.executeMethod(hostConfig, httpMethod, httpState); String contentType = httpMethod.getResponseHeader("Content-Type").getValue(); log.debug("External app responded: {0}", httpMethod.getStatusLine()); log.debug("External app contenttype: {0}", contentType); // check response code int statusCode = httpMethod.getStatusCode(); if (statusCode >= HttpURLConnection.HTTP_BAD_REQUEST) { PrintWriter writer = response.getWriter(); writer.println("External application returned status code: " + statusCode); return; } else if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM) { String location = httpMethod.getResponseHeader("Location").getValue(); if (location == null) { response.sendError(HttpURLConnection.HTTP_NOT_FOUND); return; } response.sendRedirect(rewriteURL(location, false)); return; } // open input stream InputStream in = httpMethod.getResponseBodyAsStream(); // check content type if (contentType != null && contentType.startsWith("text/html")) { rewriteHtml(in, contentType, response); } else { // binary mode if (contentType != null) { response.setContentType(contentType); } OutputStream outs = response.getOutputStream(); try { byte buf[] = new byte[8192]; int len; while ((len = in.read(buf)) != -1) { outs.write(buf, 0, len); } } finally { if (in != null) { in.close(); } } } }
From source file:com.znsx.cms.service.impl.DeviceManagerImpl.java
private List<Element> requestSubDeviceStatus(String subSn, List<String> devices) { String url = Configuration.getInstance().getProperties(subSn); // url?/*from ww w . jav a2s . co m*/ if (StringUtils.isBlank(url)) { System.out.println("Sub platform[" + subSn + "] not in config.properties !"); return new LinkedList<Element>(); } // urlIP:Port? String[] address = url.split(":"); if (address.length != 2) { System.out.println("Sub platform[" + subSn + "] config url[" + url + "] is invalid !"); return new LinkedList<Element>(); } // ? if (isSelfAddress(address[0])) { System.out.println("Sub platform[" + subSn + "] address can not be my address !"); return new LinkedList<Element>(); } StringBuffer sb = new StringBuffer(); sb.append("<Request Method=\"List_Device_Status\" Cmd=\"1017\">"); sb.append(System.getProperty("line.separator")); for (String sn : devices) { sb.append(" <Device StandardNumber=\""); sb.append(sn); sb.append("\" />"); sb.append(System.getProperty("line.separator")); } sb.append("</Request>"); String body = sb.toString(); HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true)); client.getHttpConnectionManager().getParams().setConnectionTimeout(20000); PostMethod method = new PostMethod("http://" + url + "/cms/list_device_status.xml"); System.out.println("Send request to " + url + " body is :"); System.out.println(body); try { RequestEntity entity = new StringRequestEntity(body, "application/xml", "utf8"); method.setRequestEntity(entity); client.executeMethod(method); // SAXBuilder builder = new SAXBuilder(); Document respDoc = builder.build(method.getResponseBodyAsStream()); String code = respDoc.getRootElement().getAttributeValue("Code"); if (ErrorCode.SUCCESS.equals(code)) { List<Element> list = respDoc.getRootElement().getChildren("Device"); return list; } } catch (Exception e) { e.printStackTrace(); } finally { method.releaseConnection(); } return new LinkedList<Element>(); }
From source file:com.tmwsoft.sns.web.action.MainAction.java
private String getImgHtml(String link, HttpServletRequest request) { String content = null;//from w w w .jav a 2 s. com int timeout = 10000; HttpClient httpClient = null; GetMethod getMethod = null; try { httpClient = new HttpClient(); getMethod = new GetMethod(link); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout); getMethod.setRequestHeader("Accept", "*/*"); getMethod.setRequestHeader("Accept-Language", "zh-cn"); getMethod.setRequestHeader("User-Agent", request.getHeader("User-Agent")); getMethod.setRequestHeader("Connection", "Close"); getMethod.setRequestHeader("Cookie", ""); httpClient.executeMethod(getMethod); content = getMethod.getResponseBodyAsString(); } catch (Exception e) { } finally { if (getMethod != null) { getMethod.releaseConnection(); getMethod = null; } if (httpClient != null) { httpClient.getHttpConnectionManager().closeIdleConnections(0); httpClient = null; } } return content; }
From source file:cn.jcenterhome.web.action.CpAction.java
private String getFlashImg(String link, String host, HttpServletRequest request) { String string = null;/*from ww w . java 2 s. com*/ int timeout = 10000; HttpClient httpClient = null; GetMethod getMethod = null; try { String regex = null; if ("youku.com".equals(host)) { regex = "(?i)\\+0800\\|(.*?)\\|\">"; } else if ("sina.com.cn".equals(host)) { regex = "(?i)pic: \'(.*?)\',"; } else if ("ku6.com".equals(host)) { regex = "(?i)<span class=\"s_pic\">(.*?)</span>"; } else if ("tudou.com".equals(host)) { regex = "(?i),thumbnail = \'(.*?)\'"; } else if ("56.com".equals(host)) { regex = "(?i)\"img\":\"(.*?)\\s\"\\};"; } else if ("pomoho.com".equals(host)) { regex = "var\\spic=\"(.*?)\";"; } if (regex != null) { httpClient = new HttpClient(); getMethod = new GetMethod(link); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout); getMethod.setRequestHeader("Accept", "*/*"); getMethod.setRequestHeader("Accept-Language", "zh-cn"); getMethod.setRequestHeader("User-Agent", request.getHeader("User-Agent")); getMethod.setRequestHeader("Connection", "Close"); getMethod.setRequestHeader("Cookie", ""); httpClient.executeMethod(getMethod); String content = getMethod.getResponseBodyAsString(); String matcher = getMatcherString(regex, content); if (!Common.empty(matcher)) { if ("56.com".equals(host)) { string = Common.stripCSlashes(matcher); } else { string = matcher; } } } } catch (Exception e) { } finally { if (getMethod != null) { getMethod.releaseConnection(); getMethod = null; } if (httpClient != null) { httpClient.getHttpConnectionManager().closeIdleConnections(0); httpClient = null; } } return string; }
From source file:nl.b3p.viewer.image.ImageManager.java
public ImageManager(List<CombineImageUrl> urls, int maxResponseTime, String uname, String pw) { this.maxResponseTime = maxResponseTime; if (urls == null || urls.size() <= 0) { return;//from w w w . j ava2 s . co m } MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpClient client = new HttpClient(connectionManager); client.getHttpConnectionManager().getParams().setConnectionTimeout(this.maxResponseTime); if (uname != null && pw != null) { client.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(uname, pw); AuthScope authScope = new AuthScope(host, port); client.getState().setCredentials(authScope, defaultcreds); } for (CombineImageUrl ciu : urls) { ImageCollector ic = null; if (ciu instanceof CombineWmsUrl) { ic = new ImageCollector(ciu, maxResponseTime, client, uname, pw); } else if (ciu instanceof CombineArcIMSUrl) { ic = new ArcImsImageCollector(ciu, maxResponseTime, client); } else if (ciu instanceof CombineArcServerUrl) { ic = new ArcServerImageCollector(ciu, maxResponseTime, client); } else { ic = new ImageCollector(ciu, maxResponseTime, client, uname, pw); } ics.add(ic); } }
From source file:org.alfresco.httpclient.HttpClientFactory.java
protected HttpClient constructHttpClient() { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpClient httpClient = new HttpClient(connectionManager); HttpClientParams params = httpClient.getParams(); params.setBooleanParameter(HttpConnectionParams.TCP_NODELAY, true); params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, true); if (socketTimeout != null) { params.setSoTimeout(socketTimeout); }// w w w.j a v a2 s .c om HttpConnectionManagerParams connectionManagerParams = httpClient.getHttpConnectionManager().getParams(); connectionManagerParams.setMaxTotalConnections(maxTotalConnections); connectionManagerParams.setDefaultMaxConnectionsPerHost(maxHostConnections); connectionManagerParams.setConnectionTimeout(connectionTimeout); return httpClient; }
From source file:org.apache.activemq.karaf.itest.ActiveMQBrokerNdWebConsoleFeatureTest.java
@Override protected void produceMessage(String nameAndPayload) throws Exception { HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(30000); // set credentials client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(USER, PASSWORD)); System.err.println(executeCommand("activemq:bstat").trim()); System.err.println("attempting to access web console.."); GetMethod get = new GetMethod(WEB_CONSOLE_URL + "index.jsp"); get.setDoAuthentication(true);/* w w w. j ava2 s . com*/ // Give console some time to start boolean done = false; int loop = 0; while (!done && loop < 30) { loop++; try { int code = client.executeMethod(get); if (code > 399 && code < 500) { // code 4xx we should retry System.err.println("web console not accessible yet - status code " + code); TimeUnit.SECONDS.sleep(1); } else { done = true; } } catch (Exception ignored) { } } assertEquals("get succeeded on " + get, 200, get.getStatusCode()); System.err.println("attempting publish via web console.."); // need to first get the secret get = new GetMethod(WEB_CONSOLE_URL + "send.jsp"); get.setDoAuthentication(true); int code = client.executeMethod(get); assertEquals("get succeeded on " + get, 200, code); String response = get.getResponseBodyAsString(); final String secretMarker = "<input type=\"hidden\" name=\"secret\" value=\""; String secret = response.substring(response.indexOf(secretMarker) + secretMarker.length()); secret = secret.substring(0, secret.indexOf("\"/>")); PostMethod post = new PostMethod(WEB_CONSOLE_URL + "sendMessage.action"); post.setDoAuthentication(true); post.addParameter("secret", secret); post.addParameter("JMSText", nameAndPayload); post.addParameter("JMSDestination", nameAndPayload); post.addParameter("JMSDestinationType", "queue"); // execute the send assertEquals("post succeeded, " + post, 302, client.executeMethod(post)); System.err.println(executeCommand("activemq:bstat").trim()); }
From source file:org.apache.axis2.saaj.AttachmentTest.java
private boolean isNetworkedResourceAvailable(String url) { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); client.getHttpConnectionManager().getParams().setConnectionTimeout(1000); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); try {/*from ww w. jav a 2 s.co m*/ int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { return false; } //byte[] responseBody = method.getResponseBody(); } catch (HttpException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { method.releaseConnection(); } return true; }
From source file:org.apache.axis2.saaj.SOAPConnectionTest.java
private boolean isNetworkedResourceAvailable(String url) { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); client.getHttpConnectionManager().getParams().setConnectionTimeout(1000); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); try {//from ww w .j a v a 2 s .c o m int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { return false; } } catch (HttpException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { method.releaseConnection(); } return true; }
From source file:org.apache.axis2.transport.http.AbstractHTTPSender.java
/** * This is used to get the dynamically set time out values from the * message context. If the values are not available or invalid then * the default values or the values set by the configuration will be used * * @param msgContext the active MessageContext * @param httpClient//from w w w.j a v a 2 s . c o m */ protected void initializeTimeouts(MessageContext msgContext, HttpClient httpClient) { // If the SO_TIMEOUT of CONNECTION_TIMEOUT is set by dynamically the // override the static config Integer tempSoTimeoutProperty = (Integer) msgContext.getProperty(HTTPConstants.SO_TIMEOUT); Integer tempConnTimeoutProperty = (Integer) msgContext.getProperty(HTTPConstants.CONNECTION_TIMEOUT); long timeout = msgContext.getOptions().getTimeOutInMilliSeconds(); if (tempConnTimeoutProperty != null) { int connectionTimeout = tempConnTimeoutProperty.intValue(); // timeout for initial connection httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); } else { // set timeout in client if (timeout > 0) { httpClient.getHttpConnectionManager().getParams().setConnectionTimeout((int) timeout); } } if (tempSoTimeoutProperty != null) { int soTimeout = tempSoTimeoutProperty.intValue(); // SO_TIMEOUT -- timeout for blocking reads httpClient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout); httpClient.getParams().setSoTimeout(soTimeout); } else { // set timeout in client if (timeout > 0) { httpClient.getHttpConnectionManager().getParams().setSoTimeout((int) timeout); httpClient.getParams().setSoTimeout((int) timeout); } } }