List of usage examples for org.apache.commons.httpclient HttpClient setTimeout
public void setTimeout(int paramInt)
From source file:massbank.CallCgi.java
public void run() { String progName = "CallCgi"; String msg = ""; HttpClient client = new HttpClient(); // ^CAEgl(msec)Zbg client.setTimeout(m_timeout * 1000); PostMethod method = new PostMethod(this.m_url); String strParam = ""; if (m_params != null && m_params.size() > 0) { for (Enumeration keys = m_params.keys(); keys.hasMoreElements();) { String key = (String) keys.nextElement(); if (!key.equals("inst_grp") && !key.equals("inst") && !key.equals("ms") && !key.equals("inst_grp_adv") && !key.equals("inst_adv") && !key.equals("ms_adv")) { // L?[InstrumentType,MSTypeO??Stringp??[^ String val = (String) m_params.get(key); strParam += key + "=" + val + "&"; method.addParameter(key, val); } else { // L?[InstrumentType,MSType??Stringzp??[^ String[] vals = (String[]) m_params.get(key); for (int i = 0; i < vals.length; i++) { strParam += key + "=" + vals[i] + "&"; method.addParameter(key, vals[i]); }/* w ww. ja v a 2 s. c om*/ } } strParam = strParam.substring(0, strParam.length() - 1); } try { // ?s int statusCode = client.executeMethod(method); // Xe?[^XR?[h`FbN if (statusCode != HttpStatus.SC_OK) { // G?[ msg = method.getStatusLine().toString() + "\n" + "URL : " + this.m_url; msg += "\nPARAM : " + strParam; MassBankLog.ErrorLog(progName, msg, m_context); return; } // X|X // this.result = method.getResponseBodyAsString(); /** * modification start * Use method.getResponseBodyAsStream() rather * than method.getResponseBodyAsString() (marked as deprecated) for updated HttpClient library. * Prevents logging of message: * "Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended." */ String charset = method.getResponseCharSet(); InputStream is = method.getResponseBodyAsStream(); StringBuilder sb = new StringBuilder(); String line = ""; if (is != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset)); while ((line = reader.readLine()) != null) { reader.mark(2000); String forward = reader.readLine(); if ((line.equals("") || line.equals("\n") || line.equals("OK")) && forward == null) sb.append(line); // append last line to StringBuilder else if (forward != null) sb.append(line).append("\n"); // append current line with explicit line break else sb.append(line); reader.reset(); } reader.close(); is.close(); // this.result = sb.toString().trim(); this.result = sb.toString(); // trim() deleted. because the last [\t] and [\n] are removed. if (this.result.endsWith("\n")) // remove trailing line break { int pos = this.result.lastIndexOf("\n"); this.result = this.result.substring(0, pos); } } else { this.result = ""; } /** * modification end */ } catch (Exception e) { // G?[ msg = e.toString() + "\n" + "URL : " + this.m_url; msg += "\nPARAM : " + strParam; MassBankLog.ErrorLog(progName, msg, m_context); } finally { // RlNV method.releaseConnection(); } }
From source file:com.intranet.intr.sms.SupControllerSms.java
@RequestMapping(value = "SMS.htm", method = RequestMethod.POST) public String addEstudio_post(@ModelAttribute("mensaje") sms mensaje, BindingResult result, ModelMap map) { //String mensaje=""; try {/*from www .j a va 2 s. co m*/ 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" + mensaje.getNum()); parametersList[5] = new NameValuePair("msg", "" + mensaje.getTexto()); //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(); } return "redirect:SMS.htm"; }
From source file:com.ephesoft.dcma.core.service.ServerHeartBeatMonitor.java
/** * This method will return true if the server is active other wise false. * /* w w w . ja v a 2 s . co m*/ * @param url {@link String} URL of the Heart beat service. * @return true if the serve is active other wise false. */ private boolean checkHealth(final String serviceURL) { boolean isActive = false; LOGGER.info(serviceURL); if (!EphesoftStringUtil.isNullOrEmpty(serviceURL)) { // Create an instance of HttpClient. HttpClient client = new HttpClient(); client.setConnectionTimeout(30000); client.setTimeout(30000); // Create a method instance. GetMethod method = new GetMethod(serviceURL); try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { isActive = true; } else { LOGGER.info("Method failed: " + method.getStatusLine()); } } catch (HttpException httpException) { LOGGER.error("Fatal protocol violation: " + httpException.getMessage()); } catch (IOException ioException) { LOGGER.error("Fatal transport error: " + ioException.getMessage()); } finally { // Release the connection. if (method != null) { method.releaseConnection(); } } return isActive; } return isActive; }
From source file:fr.jayasoft.ivy.url.HttpClientHandler.java
private HeadMethod doHead(URL url, int timeout) throws IOException, HttpException { HttpClient client = getClient(url); client.setTimeout(timeout); HeadMethod head = new HeadMethod(url.toExternalForm()); head.setDoAuthentication(useAuthentication(url) || useProxyAuthentication()); client.executeMethod(head);//from w ww .j a va 2s . c om return head; }
From source file:com.cloudmaster.cmp.util.AlarmSystem.transfer.HttpSender.java
public ResponseObject send(Object object, Map<String, String> paramMap) throws Exception { ResponseObject rs = new ResponseObject(); ByteArrayOutputStream bOs = null; DataOutputStream dOs = null;// ww w .ja va 2s. c o m DataInputStream dIs = null; HttpClient client; PostMethod meth = null; byte[] rawData; try { client = new HttpClient(); client.setConnectionTimeout(this.timeout); client.setTimeout(this.datatimeout); client.setHttpConnectionFactoryTimeout(this.timeout); meth = new PostMethod(paramMap.get("SERVER_URL")); // meth = new UTF8PostMethod(url); meth.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, ENCODING); // meth.addParameter(SERVER_ARGS, new String(rawData,"UTF-8")); meth.setRequestBody(object.toString()); System.out.println(object.toString()); /** * "type"="ruleSync",XML? "syncType"="***" * 1??2??3? "ruleName"="***" * XML?XML???XML */ meth.addRequestHeader("type", paramMap.get("type")); meth.addRequestHeader("syncType", paramMap.get("syncType")); meth.addRequestHeader("ruleName", URLEncoder.encode(paramMap.get("ruleName"), "UTF-8")); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); client.executeMethod(meth); dIs = new DataInputStream(meth.getResponseBodyAsStream()); if (meth.getStatusCode() == HttpStatus.SC_OK) { Header errHeader = meth.getResponseHeader(HDR_ERROR); if (errHeader != null) { rs.setError(meth.getResponseBodyAsString()); return rs; } rs = ResponseObject.fromStream(dIs); return rs; } else { meth.releaseConnection(); throw new IOException("Connection failure: " + meth.getStatusLine().toString()); } } finally { if (meth != null) { meth.releaseConnection(); } if (bOs != null) { bOs.close(); } if (dOs != null) { dOs.close(); } if (dIs != null) { dIs.close(); } } }
From source file:com.baidu.qa.service.test.client.HttpReqImpl.java
/** * use httpclient// w ww . j av a2s .c o m * @param file * @param config * @param vargen * @return */ public Object requestHttpByHttpClient(File file, Config config, VariableGenerator vargen) { FileCharsetDetector det = new FileCharsetDetector(); try { String oldcharset = det.guestFileEncoding(file); if (oldcharset.equalsIgnoreCase("UTF-8") == false) FileUtil.transferFile(file, oldcharset, "UTF-8"); } catch (Exception ex) { log.error("[change expect file charset error]:" + ex); } Map<String, String> datalist = FileUtil.getMapFromFile(file, "="); if (datalist.size() <= 1) { return true; } if (!datalist.containsKey(Constant.KW_ITEST_HOST) && !datalist.containsKey(Constant.KW_ITEST_URL)) { log.error("[wrong file]:" + file.getName() + " hasn't Url"); return null; } if (datalist.containsKey(Constant.KW_ITEST_HOST)) { this.url = datalist.get(Constant.KW_ITEST_HOST); this.hashost = true; datalist.remove(Constant.KW_ITEST_HOST); } else { String action = datalist.get(Constant.KW_ITEST_URL); if (config.getHost().lastIndexOf("/") == config.getHost().length() - 1 && action.indexOf("/") == 0) { action = action.substring(1); } this.url = config.getHost() + action; datalist.remove("itest_url"); } if (datalist.containsKey(Constant.KW_ITEST_EXPECT)) { this.itest_expect = datalist.get(Constant.KW_ITEST_EXPECT); datalist.remove(Constant.KW_ITEST_EXPECT); } if (datalist.containsKey(Constant.KW_ITEST_JSON)) { this.itest_expect_json = datalist.get(Constant.KW_ITEST_JSON); datalist.remove(Constant.KW_ITEST_JSON); } parammap = datalist; this.config = config; //HttpClient HttpClient httpClient = new HttpClient(); // httpClient.setConnectionTimeout(30000); httpClient.setTimeout(30000); httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); PostMethod postMethod = new PostMethod(url); if (hashost == false) { //cookie copy if (config.getVariable() != null && config.getVariable().containsKey(Constant.V_CONFIG_VARIABLE_COOKIE)) { postMethod.addRequestHeader(Constant.V_CONFIG_VARIABLE_COOKIE, (String) config.getVariable().get(Constant.V_CONFIG_VARIABLE_COOKIE)); log.info("[HTTP Request Cookie]" + (String) config.getVariable().get(Constant.V_CONFIG_VARIABLE_COOKIE)); } } //??keysparams??body??key=value? if (parammap.size() == 1 && (parammap.containsKey("params") || parammap.containsKey("Params"))) { String key = ""; if (parammap.containsKey("params")) { key = "params"; } else if (parammap.containsKey("Params")) { key = "Params"; } postMethod.setRequestHeader("Content-Type", "text/json;charset=utf-8"); postMethod.setRequestBody(parammap.get(key).toString()); } else { NameValuePair[] data = new NameValuePair[parammap.size()]; int i = 0; for (Map.Entry<String, String> entry : parammap.entrySet()) { log.info("[HTTP post params]" + (String) entry.getKey() + ":" + (String) entry.getValue() + ";"); if (entry.getValue().toString().contains("###")) { } else { data[i] = new NameValuePair((String) entry.getKey(), (String) entry.getValue()); } i++; } // ?postMethod postMethod.setRequestBody(data); } Assert.assertNotNull("get request error,check the input file", postMethod); String response = ""; // postMethod try { int statusCode = httpClient.executeMethod(postMethod); // HttpClient????POSTPUT??? // 301302 if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { // ??? Header locationHeader = postMethod.getResponseHeader("location"); String location = null; if (locationHeader != null) { location = locationHeader.getValue(); log.info("The page was redirected to:" + location); } else { log.info("Location field value is null."); } } //? byte[] responseBody = postMethod.getResponseBody(); if (responseBody == null) { log.error("[HTTP response is null]:please check login or servlet"); return ""; } //?utf-8 response = new String(responseBody, "UTF-8"); //? log.info("[The Post Request's Response][" + url + "]" + response); // responseoutput File resfile = FileUtil.rewriteFile(file.getParentFile().getParent() + Constant.FILENAME_OUTPUT, file.getName().substring(0, file.getName().indexOf(".")) + ".response", response); // vargen.processProps(resfile); //?? if (this.itest_expect != null && this.itest_expect.trim().length() != 0) { Assert.assertTrue( "response different with expect:[expect]:" + this.itest_expect + "[actual]:" + response, response.contains(this.itest_expect)); } // if(this.itest_expect_json!=null&&this.itest_expect_json.trim().length()!=0){ // VerifyJsonTypeResponseImpl.verifyResponseWithJson(this.itest_expect_json,response); // // } } catch (HttpException e) { //????? log.error("Please check your provided http address!" + e.getMessage()); } catch (IOException e) { //? log.error(e.getMessage()); } catch (Exception e) { log.error("[HTTP REQUEST ERROR]:", e); //case fail throw new RuntimeException("HTTP REQUEST ERROR:" + e.getMessage()); } finally { // postMethod.releaseConnection(); } return response; }
From source file:com.cloudmaster.cmp.util.AlarmSystem.transfer.HttpSender.java
public ResponseObject send(TransportObject object) throws Exception { ResponseObject rs = new ResponseObject(); ByteArrayOutputStream bOs = null; DataOutputStream dOs = null;/* ww w .j av a 2 s . c o m*/ DataInputStream dIs = null; HttpClient client; PostMethod meth = null; byte[] rawData; try { bOs = new ByteArrayOutputStream(); dOs = new DataOutputStream(bOs); object.toStream(dOs); bOs.flush(); rawData = bOs.toByteArray(); client = new HttpClient(); client.setConnectionTimeout(this.timeout); client.setTimeout(this.datatimeout); client.setHttpConnectionFactoryTimeout(this.timeout); meth = new PostMethod(object.getValue(SERVER_URL)); // meth = new UTF8PostMethod(url); meth.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, ENCODING); // meth.addParameter(SERVER_ARGS, new String(rawData,"UTF-8")); // meth.setRequestBody(new String(rawData)); // meth.setRequestBody(new String(rawData,"UTF-8")); byte[] base64Array = Base64.encode(rawData).getBytes(); meth.setRequestBody(new String(base64Array)); // System.out.println(new String(rawData)); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); client.executeMethod(meth); dIs = new DataInputStream(meth.getResponseBodyAsStream()); if (meth.getStatusCode() == HttpStatus.SC_OK) { Header errHeader = meth.getResponseHeader(HDR_ERROR); if (errHeader != null) { rs.setError(meth.getResponseBodyAsString()); return rs; } rs = ResponseObject.fromStream(dIs); return rs; } else { meth.releaseConnection(); throw new IOException("Connection failure: " + meth.getStatusLine().toString()); } } finally { if (meth != null) { meth.releaseConnection(); } if (bOs != null) { bOs.close(); } if (dOs != null) { dOs.close(); } if (dIs != null) { dIs.close(); } } }
From source file:com.dimdim.conference.application.portal.PortalServerAdapter.java
/** * @param url//from w w w . j a v a 2 s .c o m * @param arguments * @return */ protected synchronized String getURL_String(HttpClient client, String url) { GetMethod method = null; String responseBody = null; try { System.out.println("Getting URL:" + url); // System.out.println("Posting data:"+args); method = new GetMethod(url); // method.setRequestBody(args); method.setFollowRedirects(true); //execute the method client.setTimeout(2000); System.out.println("Calling url:" + url); StringBuffer buf = new StringBuffer(); client.executeMethod(method); InputStream is = method.getResponseBodyAsStream(); BufferedInputStream bis = new BufferedInputStream(is); byte[] ary = new byte[256]; int len = 0; while ((len = bis.read(ary, 0, 256)) > 0) { String str = new String(ary, 0, len); // System.out.println("Received buffer:"+str); buf.append(str); } try { bis.close(); is.close(); } catch (Exception e) { } responseBody = buf.toString(); System.out.println("Called ----:" + url); } catch (HttpException he) { he.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } //clean up the connection resources try { method.releaseConnection(); } catch (Exception ee) { // Ignore the exceptions in cleanup. } return responseBody; }
From source file:net.sf.taverna.raven.plugins.PluginManager.java
/** * Returns all the <code>Plugin</code>s available from the * <code>PluginSite</code>.// w ww . j a va 2 s .c om * * @param pluginSite * @return all the <code>Plugin</code>s available from the * <code>PluginSite</code> */ @SuppressWarnings("unchecked") public List<Plugin> getPluginsFromSite(PluginSite pluginSite) { List<Plugin> plugins = new ArrayList<Plugin>(); HttpClient client = new HttpClient(); client.setConnectionTimeout(TIMEOUT); client.setTimeout(TIMEOUT); setProxy(client); if (pluginSite.getUrl() == null) { logger.error("No plugin site URL" + pluginSite); return plugins; } URI pluginSiteURI; try { pluginSiteURI = pluginSite.getUrl().toURI(); } catch (URISyntaxException e) { logger.error("Invalid plugin site URL" + pluginSite); return plugins; } URI pluginsXML = pluginSiteURI.resolve("pluginlist.xml"); HttpMethod getPlugins = new GetMethod(pluginsXML.toString()); int statusCode; try { statusCode = client.executeMethod(getPlugins); } catch (UnknownHostException e) { logger.warn("Could not fetch plugins from non-existing host", e); return plugins; } catch (IOException e) { logger.warn("Could not fetch plugins " + pluginsXML, e); return plugins; } if (statusCode != HttpStatus.SC_OK) { logger.warn("HTTP status " + statusCode + " while getting plugins " + pluginsXML); return plugins; } Document pluginsDocument; try { pluginsDocument = new SAXBuilder().build(getPlugins.getResponseBodyAsStream()); } catch (JDOMException e) { logger.warn("Could not parse plugins " + pluginsXML, e); return plugins; } catch (IOException e) { logger.warn("Could not read plugins " + pluginsXML, e); return plugins; } List<Element> pluginList = pluginsDocument.getRootElement().getChildren("plugin"); for (Element pluginElement : pluginList) { URI pluginUri; try { pluginUri = pluginSiteURI.resolve(pluginElement.getTextTrim()); } catch (IllegalArgumentException ex) { logger.warn("Invalid plugin URI " + pluginElement.getTextTrim()); continue; } HttpMethod getPlugin = new GetMethod(pluginUri.toString()); try { statusCode = client.executeMethod(getPlugin); } catch (IOException e) { logger.warn("Could not fetch plugin " + pluginUri, e); continue; } if (statusCode != HttpStatus.SC_OK) { logger.warn("HTTP status " + statusCode + " while getting plugin " + pluginUri); continue; } Plugin plugin; try { XmlOptions xmlOptions = makeXMLOptions(); xmlOptions.setLoadReplaceDocumentElement(new QName(PLUGINS_NS, "plugin")); PluginDocument pluginDoc = PluginDocument.Factory.parse(getPlugin.getResponseBodyAsStream(), xmlOptions); plugin = Plugin.fromXmlBean(pluginDoc.getPlugin()); } catch (XmlException e1) { logger.warn("Could not parse plugin " + pluginUri, e1); continue; } catch (IOException e1) { logger.warn("Could not read plugin " + pluginUri, e1); continue; } if (checkPluginCompatibility(plugin)) { plugins.add(plugin); logger.debug("Added plugin from " + pluginUri); } else { logger.debug("Plugin deemed incompatible so not added to available plugin list"); } } logger.info("Added plugins from " + pluginSiteURI); return plugins; }
From source file:com.intranet.intr.EmpControllerProyecto.java
private void smsenvio(String nif, String mensaje) { try {/*from w ww.j av a 2s . c o 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(); } }