List of usage examples for org.apache.http.params HttpConnectionParams getConnectionTimeout
public static int getConnectionTimeout(HttpParams httpParams)
From source file:com.example.heya.couchdb.ConnectionHandler.java
/** * Forming a POST request//from ww w .j a va 2 s. c o m * * @param url * @param create * @return * @throws ClientProtocolException * @throws IOException * @throws SpikaException * @throws IllegalStateException * @throws JSONException * @throws SpikaForbiddenException */ private static InputStream httpPostRequest(String url, Object create, String userId) throws ClientProtocolException, IOException, IllegalStateException, SpikaException, JSONException, SpikaForbiddenException { HttpPost httppost = new HttpPost(url); httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); HttpConnectionParams.setConnectionTimeout(httppost.getParams(), 5000); HttpConnectionParams.setSoTimeout(httppost.getParams(), 5000); Logger.debug("TIMEOUTS", HttpConnectionParams.getConnectionTimeout(httppost.getParams()) + " " + HttpConnectionParams.getSoTimeout(httppost.getParams())); httppost.setHeader("Content-Type", "application/json"); httppost.setHeader("Encoding", "utf-8"); httppost.setHeader("database", Const.DATABASE); if (userId != null && userId.length() > 0) httppost.setHeader("user_id", userId); else { String userIdSaved = SpikaApp.getPreferences().getUserId(); if (userIdSaved != null) httppost.setHeader("user_id", userIdSaved); } String token = SpikaApp.getPreferences().getUserToken(); if (token != null && token.length() > 0) httppost.setHeader("token", token); StringEntity stringEntity = new StringEntity(create.toString(), HTTP.UTF_8); httppost.setEntity(stringEntity); print(httppost); HttpResponse response = HttpSingleton.getInstance().execute(httppost); HttpEntity entity = response.getEntity(); Logger.debug("STATUS", "" + response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() > 400) { HttpSingleton.sInstance = null; if (response.getStatusLine().getStatusCode() == 500) throw new SpikaException(getError(entity.getContent())); if (response.getStatusLine().getStatusCode() == 403) throw new SpikaForbiddenException(); throw new IOException(response.getStatusLine().getReasonPhrase()); } return entity.getContent(); }
From source file:de.ii.xtraplatform.ogc.api.wfs.client.WFSAdapter.java
private HttpResponse requestPOST(WFSOperation operation) throws ParserConfigurationException { URI url = findUrl(operation.getOperation(), WFS.METHOD.POST); HttpClient httpClient = url.getScheme().equals("https") ? this.untrustedSslHttpClient : this.httpClient; URIBuilder uri = new URIBuilder(url); String xml = operation.getPOSTXML(nsStore, versions); LOGGER.debug("{}\n{}", uri, xml); HttpPost httpPost;//from ww w . j av a 2 s . c om HttpResponse response = null; try { httpPost = new HttpPost(uri.build()); for (String key : operation.getRequestHeaders().keySet()) { httpPost.setHeader(key, operation.getRequestHeaders().get(key)); } // TODO: temporary basic auth hack if (useBasicAuth) { httpPost.addHeader("Authorization", "Basic " + basicAuthCredentials); } StringEntity xmlEntity = new StringEntity(xml, ContentType.create("text/plain", "UTF-8")); httpPost.setEntity(xmlEntity); response = httpClient.execute(httpPost, new BasicHttpContext()); // check http status checkResponseStatus(response.getStatusLine().getStatusCode(), uri); } catch (SocketTimeoutException ex) { if (ignoreTimeouts) { LOGGER.warn("POST request timed out after %d ms, URL: {} \\nRequest: {}", HttpConnectionParams.getConnectionTimeout(httpClient.getParams()), uri, xml); } response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, ""); response.setEntity(new StringEntity("", ContentType.TEXT_XML)); } catch (IOException ex) { //LOGGER.error(ERROR_IN_POST_REQUEST_TO_URL_REQUEST, uri.toString(), xml, ex); //LOGGER.debug("Error requesting URL: {}", uri.toString()); try { if (!isDefaultUrl(uri.build(), WFS.METHOD.POST)) { LOGGER.info("Removing URL: {}", uri); this.urls.remove(operation.getOperation().toString()); LOGGER.info("Retry with default URL: {}", this.urls.get("default")); return requestPOST(operation); } } catch (URISyntaxException ex0) { } LOGGER.error("Failed requesting URL: '{}'", uri); throw new ReadError("Failed requesting URL: '{}'", uri); } catch (URISyntaxException ex) { LOGGER.error("Failed requesting URL: '{}'", uri); throw new ReadError("Failed requesting URL: '{}'", uri); } catch (ReadError ex) { LOGGER.error("Failed requesting URL: '{}'", uri); throw ex; } LOGGER.debug("WFS request submitted"); return response; }
From source file:cn.org.eshow.framwork.http.ssl.AuthSSLProtocolSocketFactory.java
@Override public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" }/*from w ww .j ava 2 s. com*/ InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; }
From source file:com.groupon.odo.bmp.http.SimulatedSocketFactory.java
@Override public Socket connectSocket(Socket sock, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpParams params) throws IOException { if (remoteAddress == null) { throw new IllegalArgumentException("Target host may not be null."); }/*from w w w .j av a2 s . c o m*/ if (params == null) { throw new IllegalArgumentException("Parameters may not be null."); } if (sock == null) { sock = createSocket(null); } if ((localAddress != null)) { sock.bind(localAddress); } String hostName; if (remoteAddress instanceof HttpInetSocketAddress) { hostName = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName(); } else { hostName = resolveHostName(remoteAddress); } InetSocketAddress remoteAddr = remoteAddress; // BEGIN ODO CHANGES if (this.hostNameResolver != null) { // send request to Odo HTTP port int port = Utils.getSystemPort(Constants.SYS_HTTP_PORT); remoteAddr = new InetSocketAddress(this.hostNameResolver.resolve(hostName), port); } // END ODO CHANGES int timeout = HttpConnectionParams.getConnectionTimeout(params); try { sock.connect(remoteAddr, timeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out"); } return sock; }
From source file:de.ii.xtraplatform.ogc.api.wfs.client.WFSAdapter.java
private HttpResponse requestGET(WFSOperation operation) throws ParserConfigurationException { URI url = findUrl(operation.getOperation(), WFS.METHOD.GET); HttpClient httpClient = url.getScheme().equals("https") ? this.untrustedSslHttpClient : this.httpClient; URIBuilder uri = new URIBuilder(url); Map<String, String> params = operation.getGETParameters(nsStore, versions); for (Map.Entry<String, String> param : params.entrySet()) { uri.addParameter(param.getKey(), param.getValue()); }//from w w w.j a v a 2 s.co m LOGGER.debug("GET Request {}: {}", operation, uri); boolean retried = false; HttpGet httpGet; HttpResponse response; try { // replace the + with %20 String uristring = uri.build().toString(); uristring = uristring.replaceAll("\\+", "%20"); httpGet = new HttpGet(uristring); // TODO: temporary basic auth hack if (useBasicAuth) { httpGet.addHeader("Authorization", "Basic " + basicAuthCredentials); } response = httpClient.execute(httpGet, new BasicHttpContext()); // check http status checkResponseStatus(response.getStatusLine().getStatusCode(), uri); } catch (SocketTimeoutException ex) { if (ignoreTimeouts) { LOGGER.warn("GET request timed out after %d ms, URL: {}", HttpConnectionParams.getConnectionTimeout(httpClient.getParams()), uri); } response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, ""); response.setEntity(new StringEntity("", ContentType.TEXT_XML)); } catch (IOException ex) { try { if (!isDefaultUrl(uri.build(), WFS.METHOD.GET)) { LOGGER.info("Removing URL: {}", uri); this.urls.remove(operation.getOperation().toString()); LOGGER.info("Retry with default URL: {}", this.urls.get("default")); return requestGET(operation); } } catch (URISyntaxException ex0) { } LOGGER.error("Failed requesting URL: '{}'", uri); throw new ReadError("Failed requesting URL: '{}'", uri); } catch (URISyntaxException ex) { LOGGER.error("Failed requesting URL: '{}'", uri); throw new ReadError("Failed requesting URL: '{}'", uri); } LOGGER.debug("WFS request submitted"); return response; }
From source file:orca.ektorp.client.ContextualSSLSocketFactory.java
/** * @since 4.1/*from w w w . j av a 2 s . c om*/ * @param socket socket * @param remoteAddress remote address * @param localAddress local address * @param params HTTP params * @throws IOException in case of IO error * @throws UnknownHostException in case of unknonwn host * @throws ConnectTimeoutException in case of connect timeout * @return returns the socket */ public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (remoteAddress == null) { throw new IllegalArgumentException("Remote address may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } //Here! Socket sock = socket != null ? socket : this.socketfactory.createSocket(); if (localAddress != null) { sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params)); sock.bind(localAddress); } int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); try { sock.setSoTimeout(soTimeout); sock.connect(remoteAddress, connTimeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out"); } String hostname; if (remoteAddress instanceof HttpInetSocketAddress) { hostname = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName(); } else { hostname = remoteAddress.getHostName(); } SSLSocket sslsock; // Setup SSL layering if necessary if (sock instanceof SSLSocket) { sslsock = (SSLSocket) sock; } else { int port = remoteAddress.getPort(); sslsock = (SSLSocket) this.socketfactory.createSocket(sock, hostname, port, true); prepareSocket(sslsock); } if (this.hostnameVerifier != null) { try { this.hostnameVerifier.verify(hostname, sslsock); // verifyHostName() didn't blowup - good! } catch (IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (Exception x) { /*ignore*/ } throw iox; } } return sslsock; }
From source file:de.ii.xtraplatform.ogc.api.wfs.client.WFSAdapter.java
private HttpResponse requestGET(WfsOperation operation) throws ParserConfigurationException, TransformerException, IOException, SAXException { URI url = findUrl(operation.getOperation(), WFS.METHOD.GET); HttpClient httpClient = url.getScheme().equals("https") ? this.untrustedSslHttpClient : this.httpClient; URIBuilder uri = new URIBuilder(url); Map<String, String> params = operation.asKvp(new XMLDocumentFactory(nsStore), versions); for (Map.Entry<String, String> param : params.entrySet()) { uri.addParameter(param.getKey(), param.getValue()); }//from www .j a va 2 s.co m LOGGER.debug("GET Request {}: {}", operation, uri); boolean retried = false; HttpGet httpGet; HttpResponse response; try { // replace the + with %20 String uristring = uri.build().toString(); uristring = uristring.replaceAll("\\+", "%20"); httpGet = new HttpGet(uristring); // TODO: temporary basic auth hack if (useBasicAuth) { httpGet.addHeader("Authorization", "Basic " + basicAuthCredentials); } response = httpClient.execute(httpGet, new BasicHttpContext()); // check http status checkResponseStatus(response.getStatusLine().getStatusCode(), uri); } catch (SocketTimeoutException ex) { if (ignoreTimeouts) { LOGGER.warn("GET request timed out after %d ms, URL: {}", HttpConnectionParams.getConnectionTimeout(httpClient.getParams()), uri); } response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, ""); response.setEntity(new StringEntity("", ContentType.TEXT_XML)); } catch (IOException ex) { try { if (!isDefaultUrl(uri.build(), WFS.METHOD.GET)) { LOGGER.info("Removing URL: {}", uri); this.urls.remove(operation.getOperation().toString()); LOGGER.info("Retry with default URL: {}", this.urls.get("default")); return requestGET(operation); } } catch (URISyntaxException ex0) { } LOGGER.error("Failed requesting URL: '{}'", uri); throw new ReadError("Failed requesting URL: '{}'", uri); } catch (URISyntaxException ex) { LOGGER.error("Failed requesting URL: '{}'", uri); throw new ReadError("Failed requesting URL: '{}'", uri); } LOGGER.debug("WFS request submitted"); return response; }
From source file:no.lookout.incontrol.ModuleHost.java
public int getConnectionTimeoutMs() { return HttpConnectionParams.getConnectionTimeout(httpParams); }
From source file:org.apache.http.impl.client.StatiscicsLoggingRequestDirector.java
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException, IOException { HttpRequest orig = request;// w ww . j a v a2s . co m RequestWrapper origWrapper = wrapRequest(orig); origWrapper.setParams(params); HttpRoute origRoute = determineRoute(target, origWrapper, context); virtualHost = (HttpHost) orig.getParams().getParameter(ClientPNames.VIRTUAL_HOST); RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute); long timeout = HttpConnectionParams.getConnectionTimeout(params); boolean reuse = false; boolean done = false; try { HttpResponse response = null; while (!done) { // In this loop, the RoutedRequest may be replaced by a // followup request and route. The request and route passed // in the method arguments will be replaced. The original // request is still available in 'orig'. RequestWrapper wrapper = roureq.getRequest(); HttpRoute route = roureq.getRoute(); response = null; // See if we have a user token bound to the execution context Object userToken = context.getAttribute(ClientContext.USER_TOKEN); // Allocate connection if needed if (managedConn == null) { ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken); if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setConnectionRequest(connRequest); } try { managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException interrupted) { InterruptedIOException iox = new InterruptedIOException(); iox.initCause(interrupted); throw iox; } if (HttpConnectionParams.isStaleCheckingEnabled(params)) { // validate connection if (managedConn.isOpen()) { this.log.debug("Stale connection check"); if (managedConn.isStale()) { this.log.debug("Stale connection detected"); managedConn.close(); } } } } if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn); } try { tryConnect(roureq, context); } catch (TunnelRefusedException ex) { if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage()); } response = ex.getResponse(); break; } // Reset headers on the request wrapper wrapper.resetHeaders(); // Re-write request URI if needed rewriteRequestURI(wrapper, route); // Use virtual host if set target = virtualHost; if (target == null) { target = route.getTargetHost(); } HttpHost proxy = route.getProxyHost(); // Populate the execution context context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy); context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn); context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState); context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); synchronized (connectionStats) { ConnectionStatistics stats = new ConnectionStatistics(); stats.setConnectionState(State.OPEN); stats.setLastUsed(System.currentTimeMillis()); stats.setLastRequest(request.getRequestLine().getUri()); connectionStats.put(java.lang.System.identityHashCode(managedConn), stats); } // Run request protocol interceptors requestExec.preProcess(wrapper, httpProcessor, context); response = tryExecute(roureq, context); if (response == null) { // Need to start over continue; } // Run response protocol interceptors response.setParams(params); requestExec.postProcess(response, httpProcessor, context); // The connection is in or can be brought to a re-usable state. reuse = reuseStrategy.keepAlive(response, context); if (reuse) { // Set the idle duration of this connection long duration = keepAliveStrategy.getKeepAliveDuration(response, context); if (this.log.isDebugEnabled()) { String s; if (duration > 0) { s = "for " + duration + " " + TimeUnit.MILLISECONDS; } else { s = "indefinitely"; } this.log.debug("Connection can be kept alive " + s); } managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS); } RoutedRequest followup = handleResponse(roureq, response, context); if (followup == null) { done = true; } else { if (reuse) { // Make sure the response body is fully consumed, if present HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); // entity consumed above is not an auto-release entity, // need to mark the connection re-usable explicitly managedConn.markReusable(); } else { managedConn.close(); } // check if we can use the same connection for the followup if (!followup.getRoute().equals(roureq.getRoute())) { releaseConnection(); } roureq = followup; } if (managedConn != null && userToken == null) { userToken = userTokenHandler.getUserToken(context); context.setAttribute(ClientContext.USER_TOKEN, userToken); if (userToken != null) { managedConn.setState(userToken); } } } // while not done // check for entity, release connection if possible if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) { // connection not needed and (assumed to be) in re-usable state if (reuse) managedConn.markReusable(); releaseConnection(); } else { // install an auto-release entity HttpEntity entity = response.getEntity(); entity = new StatisticsAwareManagedEntity(entity, managedConn, reuse, this.connectionStats); response.setEntity(entity); } return response; } catch (ConnectionShutdownException ex) { InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down"); ioex.initCause(ex); throw ioex; } catch (HttpException ex) { abortConnection(); throw ex; } catch (IOException ex) { abortConnection(); throw ex; } catch (RuntimeException ex) { abortConnection(); throw ex; } }