List of usage examples for org.apache.commons.httpclient HttpClient setConnectionTimeout
public void setConnectionTimeout(int paramInt)
From source file:com.intranet.intr.EmpControllerProyecto.java
private void smsenvio(String nif, String mensaje) { try {//from w w w . j av a2 s .co m clientes cli = clientesService.ByNif(nif); //map.addAttribute("msg","success"); HttpClient client = new HttpClient(); client.setStrictMode(true); //Se fija el tiempo maximo de espera de la respuesta del servidor client.setTimeout(60000); //Se fija el tiempo maximo de espera para conectar con el servidor client.setConnectionTimeout(5000); PostMethod post = null; //Se fija la URL sobre la que enviar la peticion POST //Como ejemplo la peticion se enva a www.altiria.net/sustituirPOSTsms //Se debe reemplazar la cadena /sustituirPOSTsms por la parte correspondiente //de la URL suministrada por Altiria al dar de alta el servicio post = new PostMethod("http://www.altiria.net/api/http"); //Se fija la codificacion de caracteres en la cabecera de la peticion post.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); //Se crea la lista de parametros a enviar en la peticion POST NameValuePair[] parametersList = new NameValuePair[6]; //XX, YY y ZZ se corresponden con los valores de identificacion del //usuario en el sistema. parametersList[0] = new NameValuePair("cmd", "sendsms"); parametersList[1] = new NameValuePair("domainId", "comercial"); parametersList[2] = new NameValuePair("login", "jfruano"); parametersList[3] = new NameValuePair("passwd", "wrnkmekt"); parametersList[4] = new NameValuePair("dest", "34" + cli.getTelefono()); parametersList[5] = new NameValuePair("msg", "" + mensaje); //Se rellena el cuerpo de la peticion POST con los parametros post.setRequestBody(parametersList); int httpstatus = 0; String response = null; try { //Se enva la peticion httpstatus = client.executeMethod(post); //Se consigue la respuesta response = post.getResponseBodyAsString(); } catch (Exception e) { //Habra que prever la captura de excepciones } finally { //En cualquier caso se cierra la conexion post.releaseConnection(); } //Habra que prever posibles errores en la respuesta del servidor if (httpstatus != 200) { } else { //Se procesa la respuesta capturada en la cadena response } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.activebpel.rt.axis.bpel.handlers.AeHTTPSender.java
/** * Extracts info from message context./* www . ja v a2s . c om*/ * * @param method Post method * @param httpClient The client used for posting * @param msgContext the message context * @param tmpURL the url to post to. * * @throws Exception * @deprecated */ private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL) throws Exception { // optionally set a timeout for the request if (msgContext.getTimeout() != 0) { /* ISSUE: these are not the same, but MessageContext has only one definition of timeout */ // SO_TIMEOUT -- timeout for blocking reads httpClient.setTimeout(msgContext.getTimeout()); // timeout for initial connection httpClient.setConnectionTimeout(msgContext.getTimeout()); } // Get SOAPAction, default to "" String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; //$NON-NLS-1$ if (action == null) { action = ""; //$NON-NLS-1$ } Message msg = msgContext.getRequestMessage(); if (msg != null) { method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE, msg.getContentType(msgContext.getSOAPConstants()))); } method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"")); //$NON-NLS-1$ //$NON-NLS-2$ String userID = msgContext.getUsername(); String passwd = msgContext.getPassword(); // if UserID is not part of the context, but is in the URL, use // the one in the URL. if ((userID == null) && (tmpURL.getUserInfo() != null)) { String info = tmpURL.getUserInfo(); int sep = info.indexOf(':'); if ((sep >= 0) && (sep + 1 < info.length())) { userID = info.substring(0, sep); passwd = info.substring(sep + 1); } else { userID = info; } } if (userID != null) { Credentials cred = new UsernamePasswordCredentials(userID, passwd); httpClient.getState().setCredentials(null, null, cred); // Change #2 // // Comment out the lines below since they force all authentication // to be Basic. This is a problem if the web service you're invoking // is expecting Digest. // The following 3 lines should NOT be required. But Our SimpleAxisServer fails // during all-tests if this is missing. // StringBuffer tmpBuf = new StringBuffer(); // tmpBuf.append(userID).append(":").append((passwd == null) ? "" : passwd); // method.addRequestHeader(HTTPConstants.HEADER_AUTHORIZATION, "Basic " + Base64.encode(tmpBuf.toString().getBytes())); } // Transfer MIME headers of SOAPMessage to HTTP headers. MimeHeaders mimeHeaders = msg.getMimeHeaders(); if (mimeHeaders != null) { for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) { MimeHeader mimeHeader = (MimeHeader) i.next(); method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue()); } } // process user defined headers for information. Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS); if (userHeaderTable != null) { for (java.util.Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) { java.util.Map.Entry me = (java.util.Map.Entry) e.next(); Object keyObj = me.getKey(); if (null == keyObj) { continue; } String key = keyObj.toString().trim(); String value = me.getValue().toString().trim(); method.addRequestHeader(key, value); } } }
From source file:org.agnitas.dao.impl.VersionControlDaoImpl.java
private String fetchServerVersion(String currentVersion, String referrer) { HttpClient client = new HttpClient(); client.setConnectionTimeout(CONNECTION_TIMEOUT); HttpMethod method = new GetMethod(URL); method.setRequestHeader("referer", referrer); NameValuePair[] queryParams = new NameValuePair[1]; queryParams[0] = new NameValuePair(VERSION_KEY, currentVersion); method.setQueryString(queryParams);//from w w w.ja va2 s. c o m method.setFollowRedirects(true); String responseBody = null; try { client.executeMethod(method); responseBody = method.getResponseBodyAsString(); } catch (Exception he) { logger.error("HTTP error connecting to '" + URL + "'", he); } //clean up the connection resources method.releaseConnection(); return responseBody; }
From source file:org.apache.commons.httpclient.demo.HttpMultiPartFileUpload.java
public static void main(String[] args) throws IOException { HttpClient client = new HttpClient(); MultipartPostMethod mPost = new MultipartPostMethod(url); client.setConnectionTimeout(8000); // Send any XML file as the body of the POST request File f1 = new File("students.xml"); File f2 = new File("academy.xml"); File f3 = new File("academyRules.xml"); System.out.println("File1 Length = " + f1.length()); System.out.println("File2 Length = " + f2.length()); System.out.println("File3 Length = " + f3.length()); mPost.addParameter(f1.getName(), f1); mPost.addParameter(f2.getName(), f2); mPost.addParameter(f3.getName(), f3); //int statusCode1 = client.executeMethod(mPost); System.out.println("statusLine>>>" + mPost.getStatusLine()); ////from w ww.j a v a 2 s. c o m String response = new String(mPost.getResponseBodyAsString().getBytes("8859_1")); // System.out.println("==================================="); System.out.println(":"); System.out.println(response); System.out.println("==================================="); mPost.releaseConnection(); }
From source file:org.apache.commons.httpclient.demo.PostAFile.java
@SuppressWarnings("deprecation") public static void main(String[] args) throws IOException { HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(url); client.setConnectionTimeout(8000); // Send any XML file as the body of the POST request File f = new File("students.xml"); System.out.println("File Length = " + f.length()); postMethod.setRequestBody(new FileInputStream(f)); postMethod.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1"); //int statusCode1 = client.executeMethod(postMethod); ///*from w w w. j a v a 2 s. com*/ String response = new String(postMethod.getResponseBodyAsString().getBytes("8859_1")); // System.out.println("==================================="); System.out.println(":"); System.out.println(response); System.out.println("==================================="); System.out.println("statusLine>>>" + postMethod.getStatusLine()); postMethod.releaseConnection(); }
From source file:org.apache.roller.weblogger.util.Trackback.java
/** * Sends trackback from entry to remote URL. * See Trackback spec for details: http://www.sixapart.com/pronet/docs/trackback_spec *///from w w w . j a va 2 s . c om public RollerMessages send() throws WebloggerException { RollerMessages messages = new RollerMessages(); log.debug("Sending trackback to url - " + trackbackURL); // Construct data String title = entry.getTitle(); String excerpt = StringUtils.left(Utilities.removeHTML(entry.getDisplayContent()), 255); String url = entry.getPermalink(); String blog_name = entry.getWebsite().getName(); // build trackback post parameters as query string Map params = new HashMap(); params.put("title", URLUtilities.encode(title)); params.put("excerpt", URLUtilities.encode(excerpt)); params.put("url", URLUtilities.encode(url)); params.put("blog_name", URLUtilities.encode(blog_name)); String queryString = URLUtilities.getQueryString(params); log.debug("query string - " + queryString); // prepare http request HttpClient client = new HttpClient(); client.setConnectionTimeout(45 * 1000); HttpMethod method = new PostMethod(trackbackURL); method.setQueryString(queryString); try { // execute trackback int statusCode = client.executeMethod(method); // read response byte[] response = method.getResponseBody(); String responseString = Utilities.escapeHTML(new String(response, "UTF-8")); log.debug("result = " + statusCode + " " + method.getStatusText()); log.debug("response:\n" + responseString); if (statusCode == HttpStatus.SC_OK) { // trackback request succeeded, message will give details try { messages = parseTrackbackResponse(new String(response, "UTF-8"), messages); } catch (Exception e) { // Cannot parse response, indicates failure messages.addError("weblogEdit.trackbackErrorParsing", responseString); } } else if (statusCode == HttpStatus.SC_NOT_FOUND) { // 404, invalid trackback url messages.addError("weblogEdit.trackbackError404"); } else { // some other kind of error with url, like 500, 403, etc // just provide a generic error message and give the http response text messages.addError("weblogEdit.trackbackErrorResponse", new String[] { "" + statusCode, method.getStatusText() }); } } catch (IOException e) { // some kind of transport error sending trackback post log.debug("Error sending trackback", e); messages.addError("weblogEdit.trackbackErrorTransport"); } finally { // release used connection method.releaseConnection(); } return messages; }
From source file:org.apache.taverna.raven.plugins.ui.CheckForNoticeStartupHook.java
public boolean startup() { if (GraphicsEnvironment.isHeadless()) { return true; // if we are running headlessly just return }/*from ww w .j ava 2 s .com*/ long noticeTime = -1; long lastCheckedTime = -1; HttpClient client = new HttpClient(); client.setConnectionTimeout(TIMEOUT); client.setTimeout(TIMEOUT); PluginManager.setProxy(client); String message = null; try { URI noticeURI = new URI(BASE_URL + "/" + version + "/" + SUFFIX); HttpMethod method = new GetMethod(noticeURI.toString()); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.warn("HTTP status " + statusCode + " while getting " + noticeURI); return true; } String noticeTimeString = null; Header h = method.getResponseHeader("Last-Modified"); message = method.getResponseBodyAsString(); if (h != null) { noticeTimeString = h.getValue(); noticeTime = format.parse(noticeTimeString).getTime(); logger.info("NoticeTime is " + noticeTime); } } catch (URISyntaxException e) { logger.error("URI problem", e); return true; } catch (IOException e) { logger.info("Could not read notice", e); } catch (ParseException e) { logger.error("Could not parse last-modified time", e); } if (lastNoticeCheckFile.exists()) { lastCheckedTime = lastNoticeCheckFile.lastModified(); } if ((message != null) && (noticeTime != -1)) { if (noticeTime > lastCheckedTime) { // Show the notice dialog JOptionPane.showMessageDialog(null, message, "Taverna notice", JOptionPane.INFORMATION_MESSAGE, WorkbenchIcons.tavernaCogs64x64Icon); try { FileUtils.touch(lastNoticeCheckFile); } catch (IOException e) { logger.error("Unable to touch file", e); } } } return true; }
From source file:org.eclipse.lyo.samples.sharepoint.SharepointConnector.java
public int createDocument(HttpServletResponse response, String library, FileItem item) throws UnrecognizedValueTypeException, ShareServerException { // System.out.println("createDocument: uri='" + uri + "'"); //SharepointResource sharepointResource = new SharepointResource(uri); // String filename = resource.getSource(); // /*w w w . j av a 2s . com*/ // OEntity newProduct = odatac.createEntity("Empire").properties(OProperties.int32("Id", 10)) // .properties(OProperties.string("Name", filename)) // .properties(OProperties.string("ContentType","Document")) // .properties(OProperties.string("Title","Architecture")) // .properties(OProperties.string("ApprovalStatus","2")) // .properties(OProperties.string("Path","/Empire")) // .execute(); // no obvious API in odata4j to create a document, default apache http Create HttpClient client = new HttpClient(); client.getParams().setParameter("http.useragent", "Test Client"); BufferedReader br = null; int returnCode = 500; PostMethod method = null; try { client.setConnectionTimeout(8000); method = new PostMethod(SharepointInitializer.getSharepointUri() + "/" + library); String userPassword = SharepointInitializer.getUsername() + ":" + SharepointInitializer.getPassword(); String encoding = Base64.encodeBase64String(userPassword.getBytes()); encoding = encoding.replaceAll("\r\n?", ""); method.setRequestHeader("Authorization", "Basic " + encoding); method.addRequestHeader("Content-type", item.getContentType()); method.addRequestHeader(IConstants.HDR_SLUG, "/" + library + "/" + item.getName()); //InputStream is = new FileInputStream("E:\\odata\\sharepoint\\DeathStarTest.doc"); RequestEntity entity = new InputStreamRequestEntity(item.getInputStream(), "application/msword"); method.setRequestEntity(entity); method.setDoAuthentication(true); returnCode = client.executeMethod(method); if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) { System.err.println("The Post method is not implemented by this URI"); // still consume the response body method.getResponseBodyAsString(); } else { //br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); InputStream is = method.getResponseBodyAsStream(); //br = new BufferedReader(new InputStreamReader(is)); // String readLine; // while(((readLine = br.readLine()) != null)) { // System.out.println(readLine); // } response.setContentType("text/html"); //response.setContentType("application/atom+xml"); //response.setContentLength(is.getBytes().length); response.setStatus(IConstants.SC_OK); //response.getWriter().write("<html><head><title>hello world</title></head><body><p>hello world!</p></body></html>"); //response.getWriter().write(method.getResponseBodyAsString()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(is); Element root = doc.getDocumentElement(); System.out.println("Root element of the doc is " + root.getNodeName()); // String msftdPrefix = "http://schemas.microsoft.com/ado/2007/08/dataservices"; // String msftmPrefix = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"; String id = null; String name = null; NodeList nl = root.getElementsByTagName("d:Id"); if (nl.getLength() > 0) { id = nl.item(0).getFirstChild().getNodeValue(); } //nl = root.getElementsByTagName("d:ContentType"); //if (nl.getLength() > 0) { // type = nl.item(0).getFirstChild().getNodeValue(); //} nl = root.getElementsByTagName("d:Name"); if (nl.getLength() > 0) { name = nl.item(0).getFirstChild().getNodeValue(); } response.getWriter().write("<html>"); response.getWriter().write("<head>"); response.getWriter().write("</head>"); response.getWriter().write("<body>"); response.getWriter().write("<p>" + name + " was created with an Id =" + id + "</p>"); response.getWriter().write("</body>"); response.getWriter().write("</html>"); //response.getWriter().write(is.content); //String readLine; //while(((readLine = br.readLine()) != null)) { // response.getWriter().write(readLine); //} //response.setContentType(IConstants.CT_XML); //response.getWriter().write(is.toString()); //response.setStatus(IConstants.SC_OK); //test // String readLine; // while(((readLine = br.readLine()) != null)) { // System.out.println(readLine); // } } } catch (Exception e) { System.err.println(e); e.printStackTrace(); } finally { if (method != null) method.releaseConnection(); if (br != null) try { br.close(); } catch (Exception fe) { } } return returnCode; }
From source file:org.infoglue.cms.applications.managementtool.actions.UploadPortletAction.java
/** * Report to deliver engines that a portlet has been uploaded * * @param contentId/*from ww w . ja v a 2 s .c om*/ * contentId of portlet */ private void updateDeliverEngines(Integer digitalAssetId) { List allUrls = CmsPropertyHandler.getInternalDeliveryUrls(); allUrls.addAll(CmsPropertyHandler.getPublicDeliveryUrls()); Iterator urlIterator = allUrls.iterator(); while (urlIterator.hasNext()) { String url = (String) urlIterator.next() + "/DeployPortlet.action"; try { HttpClient client = new HttpClient(); // establish a connection within 5 seconds client.setConnectionTimeout(5000); // set the default credentials HttpMethod method = new GetMethod(url); method.setQueryString("digitalAssetId=" + digitalAssetId); method.setFollowRedirects(true); // execute the method client.executeMethod(method); StatusLine status = method.getStatusLine(); if (status != null && status.getStatusCode() == 200) { log.info("Successfully deployed portlet at " + url); } else { log.warn("Failed to deploy portlet at " + url + ": " + status); } //clean up the connection resources method.releaseConnection(); } catch (Exception e) { e.printStackTrace(); } } /* Properties props = CmsPropertyHandler.getProperties(); for (Enumeration keys = props.keys(); keys.hasMoreElements();) { String key = (String) keys.nextElement(); if (key.startsWith(PORTLET_DEPLOY_PREFIX)) { String url = props.getProperty(key); try { HttpClient client = new HttpClient(); //establish a connection within 5 seconds client.setConnectionTimeout(5000); //set the default credentials HttpMethod method = new GetMethod(url); method.setQueryString("digitalAssetId=" + digitalAssetId); method.setFollowRedirects(true); //execute the method client.executeMethod(method); StatusLine status = method.getStatusLine(); if (status != null && status.getStatusCode() == 200) { log.info("Successfully deployed portlet at " + url); } else { log.warn("Failed to deploy portlet at " + url + ": " + status); } //clean up the connection resources method.releaseConnection(); } catch (Throwable e) { log.error(e.getMessage(), e); } } } */ }
From source file:org.methodize.nntprss.feed.Channel.java
private HttpClient getHttpClient() { HttpClient httpClient = new HttpClient(); httpClient.setConnectionTimeout(HTTP_CONNECTION_TIMEOUT); httpClient.setTimeout(HTTP_CONNECTION_TIMEOUT); // Initialize user id / password for protected feeds if (url.getUserInfo() != null) { httpClient.getState().setCredentials(null, null, new UsernamePasswordCredentials(URLDecoder.decode(url.getUserInfo()))); }//ww w . ja v a2 s. c o m return httpClient; }