List of usage examples for org.apache.commons.httpclient.params HttpMethodParams SO_TIMEOUT
String SO_TIMEOUT
To view the source code for org.apache.commons.httpclient.params HttpMethodParams SO_TIMEOUT.
Click Source Link
From source file:buildhappy.tools.DownloadFile.java
/** * URL/*www. java2 s .c o m*/ */ public String downloadFile(String url) { String filePath = null; //1.?HttpClient?? HttpClient client = new HttpClient(); //5s client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); //2.?GetMethod? GetMethod getMethod = new GetMethod(url); //get5s getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000); //?? getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); //3.http get try { int statusCode = client.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed:" + getMethod.getStatusLine()); filePath = null; } //4.?HTTP? InputStream in = getMethod.getResponseBodyAsStream(); BufferedInputStream buffIn = new BufferedInputStream(in); //byte[] responseBody = null; String responseBody = null; StringBuffer strBuff = new StringBuffer(); byte[] b = new byte[1024]; int readByte = 0; while ((readByte = buffIn.read(b)) != -1) { strBuff.append(new String(b)); } responseBody = strBuff.toString(); //buffIn.read(responseBody, off, len) //byte[] responseBody = getMethod.getResponseBody(); //?url???? filePath = "temp\\" + getFileNameByUrl(url, getMethod.getResponseHeader("Content-Type").getValue()); System.out.println(filePath + "--size:" + responseBody.length()); saveToLocal(responseBody.getBytes(), filePath); } catch (HttpException e) { System.out.println("check your http address"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // getMethod.releaseConnection(); } return filePath; }
From source file:edu.internet2.middleware.grouper.changeLog.esb2.consumer.EsbHttpPublisher.java
@Override public boolean dispatchEvent(String eventJsonString, String consumerName) { // TODO Auto-generated method stub String urlString = GrouperLoaderConfig .getPropertyString("changeLog.consumer." + consumerName + ".publisher.url"); String username = GrouperLoaderConfig .getPropertyString("changeLog.consumer." + consumerName + ".publisher.username", ""); String password = GrouperLoaderConfig .getPropertyString("changeLog.consumer." + consumerName + ".publisher.password", ""); if (LOG.isDebugEnabled()) { LOG.debug("Consumer name: " + consumerName + " sending " + GrouperUtil.indent(eventJsonString, false) + " to " + urlString); }/*w w w. j a v a2 s . co m*/ int retries = GrouperLoaderConfig .getPropertyInt("changeLog.consumer." + consumerName + ".publisher.retries", 0); int timeout = GrouperLoaderConfig .getPropertyInt("changeLog.consumer." + consumerName + ".publisher.timeout", 60000); PostMethod post = new PostMethod(urlString); post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retries, false)); post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(timeout)); post.setRequestHeader("Content-Type", "application/json; charset=utf-8"); RequestEntity requestEntity; try { requestEntity = new StringRequestEntity(eventJsonString, "application/json", "utf-8"); post.setRequestEntity(requestEntity); HttpClient httpClient = new HttpClient(); if (!(username.equals(""))) { if (LOG.isDebugEnabled()) { LOG.debug("Authenticating using basic auth"); } URL url = new URL(urlString); httpClient.getState().setCredentials(new AuthScope(null, url.getPort(), null), new UsernamePasswordCredentials(username, password)); httpClient.getParams().setAuthenticationPreemptive(true); post.setDoAuthentication(true); } int statusCode = httpClient.executeMethod(post); if (statusCode == 200) { if (LOG.isDebugEnabled()) { LOG.debug("Status code 200 recieved, event sent OK"); } return true; } else { if (LOG.isDebugEnabled()) { LOG.debug("Status code " + statusCode + " recieved, event send failed"); } return false; } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; }
From source file:com.gagein.crawler.FileDownLoader.java
public String downloadLink(String url, HtmlFileBean hfb) { /* 1.? HttpClinet ? */ HttpClient httpClient = new HttpClient(); // Http 5s//from w w w . j a va2s. co m httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); /* 2.? GetMethod ? */ GetMethod getMethod = new GetMethod(url); // get 5s getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000); // ?? getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); /* 3. HTTP GET */ try { int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + getMethod.getStatusLine()); } /* 4.? HTTP ? */ byte[] responseBody = getMethod.getResponseBody();// ? // ? url ???? url = FileUtils.getFileNameByUrl(url); saveToLocal(responseBody, hfb.getDirPath() + File.separator + url); } catch (HttpException e) { // ????? logger.debug("Please check your provided http " + "address!"); e.printStackTrace(); } catch (IOException e) { // ? logger.debug("?"); e.printStackTrace(); } finally { // logger.debug("=======================" + url + "=============?"); getMethod.releaseConnection(); } return hfb.getDirPath() + url; }
From source file:net.oauth.client.httpclient3.HttpClient3.java
public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException { final String method = request.method; final String url = request.url.toExternalForm(); final InputStream body = request.getBody(); final boolean isDelete = DELETE.equalsIgnoreCase(method); final boolean isPost = POST.equalsIgnoreCase(method); final boolean isPut = PUT.equalsIgnoreCase(method); byte[] excerpt = null; HttpMethod httpMethod;// w w w .j ava 2 s . c o m if (isPost || isPut) { EntityEnclosingMethod entityEnclosingMethod = isPost ? new PostMethod(url) : new PutMethod(url); if (body != null) { ExcerptInputStream e = new ExcerptInputStream(body); String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH); entityEnclosingMethod.setRequestEntity((length == null) ? new InputStreamRequestEntity(e) : new InputStreamRequestEntity(e, Long.parseLong(length))); excerpt = e.getExcerpt(); } httpMethod = entityEnclosingMethod; } else if (isDelete) { httpMethod = new DeleteMethod(url); } else { httpMethod = new GetMethod(url); } for (Map.Entry<String, Object> p : parameters.entrySet()) { String name = p.getKey(); String value = p.getValue().toString(); if (FOLLOW_REDIRECTS.equals(name)) { httpMethod.setFollowRedirects(Boolean.parseBoolean(value)); } else if (READ_TIMEOUT.equals(name)) { httpMethod.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, Integer.parseInt(value)); } } for (Map.Entry<String, String> header : request.headers) { httpMethod.addRequestHeader(header.getKey(), header.getValue()); } HttpClient client = clientPool.getHttpClient(new URL(httpMethod.getURI().toString())); client.executeMethod(httpMethod); return new HttpMethodResponse(httpMethod, excerpt, request.getContentCharset()); }
From source file:ch.cyberduck.core.http.HTTP3Session.java
protected HostConfiguration getHostConfiguration(Host host) { int port = host.getPort(); final HostConfiguration configuration = new StickyHostConfiguration(); if ("https".equals(host.getProtocol().getScheme())) { if (-1 == port) { port = 443;/*from w ww .ja v a2s. com*/ } // Configuration with custom socket factory using the trust manager configuration.setHost(host.getHostname(), port, new org.apache.commons.httpclient.protocol.Protocol(host.getProtocol().getScheme(), new SSLSocketFactory(this.getTrustManager(host.getHostname())), port)); if (Preferences.instance().getBoolean("connection.proxy.enable")) { final Proxy proxy = ProxyFactory.instance(); if (proxy.isHTTPSProxyEnabled(host)) { configuration.setProxy(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host)); } } } else if ("http".equals(host.getProtocol().getScheme())) { if (-1 == port) { port = 80; } configuration.setHost(host.getHostname(), port, new org.apache.commons.httpclient.protocol.Protocol( host.getProtocol().getScheme(), new DefaultProtocolSocketFactory(), port)); if (Preferences.instance().getBoolean("connection.proxy.enable")) { final Proxy proxy = ProxyFactory.instance(); if (proxy.isHTTPProxyEnabled(host)) { configuration.setProxy(proxy.getHTTPProxyHost(host), proxy.getHTTPProxyPort(host)); } } } final HostParams parameters = configuration.getParams(); parameters.setParameter(HttpMethodParams.USER_AGENT, this.getUserAgent()); parameters.setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); parameters.setParameter(HttpMethodParams.SO_TIMEOUT, this.timeout()); parameters.setParameter(HttpMethodParams.CREDENTIAL_CHARSET, "ISO-8859-1"); parameters.setParameter(HttpClientParams.MAX_REDIRECTS, 10); return configuration; }
From source file:net.bpelunit.framework.control.run.TestCaseRunner.java
/** * //from w w w. j av a2 s.c o m * Sends a synchronous message, waits for the result, and returns the * result. This method blocks until either a result has been retrieved, a * send error has occurred, or the thread was interrupted. * * @param message * the message to be sent * @return the resulting incoming message * @throws SynchronousSendException * @throws InterruptedException */ public IncomingMessage sendMessageSynchronous(OutgoingMessage message) throws SynchronousSendException, InterruptedException { PostMethod method = new PostMethod(message.getTargetURL()); // Set parameters: // -> Do not retry // -> Socket timeout to default timeout value. method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, Integer.valueOf(BPELUnitRunner.getTimeout())); method.addRequestHeader("SOAPAction", "\"" + message.getSOAPHTTPAction() + "\""); RequestEntity entity; try { entity = new StringRequestEntity(message.getMessageAsString(), BPELUnitConstants.TEXT_XML_CONTENT_TYPE, BPELUnitConstants.DEFAULT_HTTP_CHARSET); } catch (UnsupportedEncodingException e) { // cannot happen since we use the default HTTP Encoding. throw new SynchronousSendException("Unsupported encoding when trying to post message to web service.", e); } for (String option : message.getProtocolOptionNames()) { method.addRequestHeader(option, message.getProtocolOption(option)); } method.setRequestEntity(entity); try { // Execute the method. int statusCode = fClient.executeMethod(method); InputStream in = method.getResponseBodyAsStream(); IncomingMessage returnMsg = new IncomingMessage(); returnMsg.setStatusCode(statusCode); returnMsg.setMessage(in); return returnMsg; } catch (Exception e) { if (isAborting()) { throw new InterruptedException(); } else { throw new SynchronousSendException(e); } } finally { // Release the connection. method.releaseConnection(); } }
From source file:com.taobao.diamond.sdkapi.impl.DiamondSDKManagerImpl.java
private ContextResult processPulishByDefinedServerId(String dataId, String groupName, String context, String serverId) {/*from ww w . j a v a 2 s. co m*/ ContextResult response = new ContextResult(); // if (!login(serverId)) { response.setSuccess(false); response.setStatusMsg(",serverId"); return response; } if (log.isDebugEnabled()) log.debug("processPulishByDefinedServerId(" + dataId + "," + groupName + "," + context + "," + serverId + ")"); String postUrl = "/diamond-server/admin.do?method=postConfig"; PostMethod post = new PostMethod(postUrl); // post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout); try { NameValuePair dataId_value = new NameValuePair("dataId", dataId); NameValuePair group_value = new NameValuePair("group", groupName); NameValuePair content_value = new NameValuePair("content", context); // post.setRequestBody(new NameValuePair[] { dataId_value, group_value, content_value }); // ConfigInfo configInfo = new ConfigInfo(); configInfo.setDataId(dataId); configInfo.setGroup(groupName); configInfo.setContent(context); if (log.isDebugEnabled()) log.debug("ConfigInfo: " + configInfo); // response.setConfigInfo(configInfo); // http int status = client.executeMethod(post); response.setReceiveResult(post.getResponseBodyAsString()); response.setStatusCode(status); log.info("" + status + "," + post.getResponseBodyAsString()); if (status == HttpStatus.SC_OK) { response.setSuccess(true); response.setStatusMsg(""); log.info(", dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId); } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) { response.setSuccess(false); response.setStatusMsg(", :" + require_timeout + ""); log.error(":" + require_timeout + ", dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId); } else { response.setSuccess(false); response.setStatusMsg(", :" + status); log.error(":" + response.getReceiveResult() + ",dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId); } } catch (HttpException e) { response.setStatusMsg("HttpException" + e.getMessage()); log.error("HttpException: dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId, e); } catch (IOException e) { response.setStatusMsg("IOException" + e.getMessage()); log.error("IOException: dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId, e); } finally { // post.releaseConnection(); } return response; }
From source file:com.bigdata.rdf.sail.remoting.GraphRepositoryClient.java
private HttpClient getHttpClient() { if (httpClient == null) { httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); httpClient.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(300000)); // httpClient.getParams().setParameter(HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, // new Integer(300000)); httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new NeverRetryHandler()); httpClient.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, new Long(300000)); httpClient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, new Integer(300000)); httpClient.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, new Integer(300000)); }/*from w ww . j ava 2 s. co m*/ if (proxyHost != null) { httpClient.getHostConfiguration().setProxyHost(proxyHost); } return httpClient; }
From source file:cn.leancloud.diamond.sdkapi.impl.DiamondSDKManagerImpl.java
private ContextResult processPulishByDefinedServerId(String dataId, String groupName, String context, String serverId) {//from w ww . j a v a 2 s .c o m ContextResult response = new ContextResult(); // if (!login(serverId)) { response.setSuccess(false); response.setStatusMsg(",??serverId?"); return response; } if (log.isDebugEnabled()) log.debug("processPulishByDefinedServerId(" + dataId + "," + groupName + "," + context + "," + serverId + ")?"); String postUrl = "/diamond-server/admin.do?method=postConfig"; PostMethod post = new PostMethod(postUrl); // post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout); try { NameValuePair dataId_value = new NameValuePair("dataId", dataId); NameValuePair group_value = new NameValuePair("group", groupName); NameValuePair content_value = new NameValuePair("content", context); // ? post.setRequestBody(new NameValuePair[] { dataId_value, group_value, content_value }); // ? ConfigInfo configInfo = new ConfigInfo(); configInfo.setDataId(dataId); configInfo.setGroup(groupName); configInfo.setContent(context); if (log.isDebugEnabled()) log.debug("?ConfigInfo: " + configInfo); // ?? response.setConfigInfo(configInfo); // http?? int status = client.executeMethod(post); response.setReceiveResult(post.getResponseBodyAsString()); response.setStatusCode(status); log.info("??" + status + ",?" + post.getResponseBodyAsString()); if (status == HttpStatus.SC_OK) { response.setSuccess(true); response.setStatusMsg("???"); log.info("???, dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId); } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) { response.setSuccess(false); response.setStatusMsg("??, :" + require_timeout + ""); log.error("??:" + require_timeout + ", dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId); } else { response.setSuccess(false); response.setStatusMsg("??, ??:" + status); log.error("??:" + response.getReceiveResult() + ",dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId); } } catch (HttpException e) { response.setStatusMsg("???HttpException" + e.getMessage()); log.error("???HttpException: dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId, e); } catch (IOException e) { response.setStatusMsg("???IOException" + e.getMessage()); log.error("???IOException: dataId=" + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId, e); } finally { // ? post.releaseConnection(); } return response; }
From source file:com.baidu.qa.service.test.client.SoapReqImpl.java
private static String sendSoapViaHttps(String hosturl, String ip, int port, String action, String method, String xml) {// w w w .j a v a 2 s . c om String reqURL = "https://" + ip + ":" + port + action; // Map<String, String> params = null; long responseLength = 0; // ? String responseContent = null; // ? HttpClient httpClient = new DefaultHttpClient(); // httpClient httpClient.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000); X509TrustManager xtm = new X509TrustManager() { // TrustManager public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; try { // TLS1.0SSL3.0??TLSSSL?SSLContext SSLContext ctx = SSLContext.getInstance("TLS"); // TrustManager??TrustManager?SSLSocket ctx.init(null, new TrustManager[] { xtm }, null); // SSLSocketFactory SSLSocketFactory socketFactory = new SSLSocketFactory(ctx); // SchemeRegistrySSLSocketFactoryHttpClient httpClient.getConnectionManager().getSchemeRegistry() .register(new Scheme("https", port, socketFactory)); HttpPost httpPost = new HttpPost(reqURL); // HttpPost // add the 3 headers below httpPost.addHeader("Accept-Encoding", "gzip,deflate"); httpPost.addHeader("SOAPAction", hosturl + action + method);// SOAP action httpPost.addHeader("uuid", "itest");// for editor token of DR-Api // HttpEntity requestBody = new // ByteArrayEntity(xml.getBytes("UTF-8"));// TODO byte[] b = xml.getBytes("UTF-8"); // must be UTF-8 InputStream is = new ByteArrayInputStream(b, 0, b.length); HttpEntity requestBody = new InputStreamEntity(is, b.length, ContentType.create("text/xml;charset=UTF-8"));// must be // UTF-8 httpPost.setEntity(requestBody); log.info(">> Request URI: " + httpPost.getRequestLine().getUri()); HttpResponse response = httpClient.execute(httpPost); // POST HttpEntity entity = response.getEntity(); // ?? if (null != entity) { responseLength = entity.getContentLength(); String contentEncoding = null; Header ce = response.getEntity().getContentEncoding(); if (ce != null) { contentEncoding = ce.getValue(); } if (contentEncoding != null && contentEncoding.indexOf("gzip") != -1) { GZIPInputStream gzipin = new GZIPInputStream(response.getEntity().getContent()); Scanner in = new Scanner(new InputStreamReader(gzipin, "UTF-8")); StringBuilder sb = new StringBuilder(); while (in.hasNextLine()) { sb.append(in.nextLine()).append(System.getProperty("line.separator")); } responseContent = sb.toString(); } else { responseContent = EntityUtils.toString(response.getEntity(), "UTF-8"); } EntityUtils.consume(entity); // Consume response content } log.info("?: " + httpPost.getURI()); log.info("??: " + response.getStatusLine()); log.info("?: " + responseLength); log.info("?: " + responseContent); } catch (KeyManagementException e) { log.error(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { log.error(e.getMessage(), e); } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); } catch (ClientProtocolException e) { log.error(e.getMessage(), e); } catch (ParseException e) { log.error(e.getMessage(), e); } catch (IOException e) { log.error(e.getMessage(), e); } finally { httpClient.getConnectionManager().shutdown(); // ,? return responseContent; } }