org.apache.commons.httpclient.HttpConnection Java Examples
The following examples show how to use
org.apache.commons.httpclient.HttpConnection.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DavExchangeSession.java From davmail with GNU General Public License v2.0 | 6 votes |
/** * @inheritDoc */ @Override public void updateMessage(ExchangeSession.Message message, Map<String, String> properties) throws IOException { PropPatchMethod patchMethod = new PropPatchMethod(encodeAndFixUrl(message.permanentUrl), buildProperties(properties)) { @Override protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) { // ignore response body, sometimes invalid with exchange mapi properties } }; try { int statusCode = httpClient.executeMethod(patchMethod); if (statusCode != HttpStatus.SC_MULTI_STATUS) { throw new DavMailException("EXCEPTION_UNABLE_TO_UPDATE_MESSAGE"); } } finally { patchMethod.releaseConnection(); } }
Example #2
Source File: IdleConnectionHandler.java From knopflerfish.org with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Closes connections that have been idle for at least the given amount of time. * * @param idleTime the minimum idle time, in milliseconds, for connections to be closed */ public void closeIdleConnections(long idleTime) { // the latest time for which connections will be closed long idleTimeout = System.currentTimeMillis() - idleTime; if (LOG.isDebugEnabled()) { LOG.debug("Checking for connections, idleTimeout: " + idleTimeout); } Iterator connectionIter = connectionToAdded.keySet().iterator(); while (connectionIter.hasNext()) { HttpConnection conn = (HttpConnection) connectionIter.next(); Long connectionTime = (Long) connectionToAdded.get(conn); if (connectionTime.longValue() <= idleTimeout) { if (LOG.isDebugEnabled()) { LOG.debug("Closing connection, connection time: " + connectionTime); } connectionIter.remove(); conn.close(); } } }
Example #3
Source File: StreamedPostMethod.java From jrpip with Apache License 2.0 | 6 votes |
@Override protected void writeRequest(HttpState state, HttpConnection conn) throws IOException { try { BufferedChunkedOutputStream bufferedChunkedOutputStream = new BufferedChunkedOutputStream(conn, state, this); this.writer.write(bufferedChunkedOutputStream); bufferedChunkedOutputStream.finish(); conn.flushRequestOutputStream(); } catch (IOException e) { this.cleanupConnection(conn); throw e; } }
Example #4
Source File: ThreadLocalHttpConnectionManager.java From webarchive-commons with Apache License 2.0 | 6 votes |
public void run() { try { while (!Thread.interrupted()) { Thread.sleep(SLEEP_INTERVAL); List<HttpConnection> s; synchronized (connections) { s = connections; connections = new ArrayList<HttpConnection>(); } logger.log(Level.INFO, "Closing " + s.size() + " HttpConnections"); for(final Iterator<HttpConnection> it = s.iterator(); it.hasNext();) { HttpConnection conn = it.next(); conn.close(); conn.setHttpConnectionManager(null); it.remove(); } } } catch (InterruptedException e) { return; } }
Example #5
Source File: ThreadLocalHttpConnectionManager.java From webarchive-commons with Apache License 2.0 | 6 votes |
/** * Since the same connection is about to be reused, make sure the * previous request was completely processed, and if not * consume it now. * @param conn The connection * @return true, if the connection is reusable */ private static boolean finishLastResponse(final HttpConnection conn) { InputStream lastResponse = conn.getLastResponseInputStream(); if(lastResponse != null) { conn.setLastResponseInputStream(null); try { lastResponse.close(); return true; } catch (IOException ioe) { // force reconnect. return false; } } else { return false; } }
Example #6
Source File: BufferedPostMethod.java From jrpip with Apache License 2.0 | 6 votes |
@Override protected void writeRequest(HttpState state, HttpConnection conn) throws IOException { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(2048); this.writer.write(outputStream); outputStream.close(); this.result = outputStream.toByteArray(); this.setRequestEntity(this); this.writeRequestLine(state, conn); this.writeRequestHeaders(state, conn); conn.writeLine(); // close head // make sure the status line and headers have been sent conn.flushRequestOutputStream(); this.writeRequestBody(state, conn); conn.flushRequestOutputStream(); } catch (IOException e) { this.cleanupConnection(conn); throw e; } }
Example #7
Source File: ExpectContinueMethod.java From knopflerfish.org with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Sets the <tt>Expect</tt> header if it has not already been set, * in addition to the "standard" set of headers. * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. */ protected void addRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter ExpectContinueMethod.addRequestHeaders(HttpState, HttpConnection)"); super.addRequestHeaders(state, conn); // If the request is being retried, the header may already be present boolean headerPresent = (getRequestHeader("Expect") != null); // See if the expect header should be sent // = HTTP/1.1 or higher // = request body present if (getParams().isParameterTrue(HttpMethodParams.USE_EXPECT_CONTINUE) && getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1) && hasRequestContent()) { if (!headerPresent) { setRequestHeader("Expect", "100-continue"); } } else { if (headerPresent) { removeRequestHeader("Expect"); } } }
Example #8
Source File: HttpClient3RequestWrapper.java From pinpoint with Apache License 2.0 | 6 votes |
private static String getHttpUrl(final String host, final int port, final URI uri, final HttpConnection httpConnection) throws URIException { final Protocol protocol = httpConnection.getProtocol(); if (protocol == null) { return uri.getURI(); } final StringBuilder sb = new StringBuilder(); final String scheme = protocol.getScheme(); sb.append(scheme).append("://"); sb.append(host); // if port is default port number. if (port != SKIP_DEFAULT_PORT) { sb.append(':').append(port); } sb.append(uri.getURI()); return sb.toString(); }
Example #9
Source File: MultipartPostMethod.java From knopflerfish.org with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Adds a <tt>Content-Type</tt> request header. * * @param state current state of http requests * @param conn the connection to use for I/O * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * * @since 3.0 */ protected void addContentTypeRequestHeader(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter EntityEnclosingMethod.addContentTypeRequestHeader(" + "HttpState, HttpConnection)"); if (!parameters.isEmpty()) { StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE); if (Part.getBoundary() != null) { buffer.append("; boundary="); buffer.append(Part.getBoundary()); } setRequestHeader("Content-Type", buffer.toString()); } }
Example #10
Source File: EntityEnclosingMethod.java From knopflerfish.org with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Generates <tt>Content-Length</tt> or <tt>Transfer-Encoding: Chunked</tt> * request header, as long as no <tt>Content-Length</tt> request header * already exists. * * @param state current state of http requests * @param conn the connection to use for I/O * * @throws IOException when errors occur reading or writing to/from the * connection * @throws HttpException when a recoverable error occurs */ protected void addContentLengthRequestHeader(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter EntityEnclosingMethod.addContentLengthRequestHeader(" + "HttpState, HttpConnection)"); if ((getRequestHeader("content-length") == null) && (getRequestHeader("Transfer-Encoding") == null)) { long len = getRequestContentLength(); if (len < 0) { if (getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1)) { addRequestHeader("Transfer-Encoding", "chunked"); } else { throw new ProtocolException(getEffectiveVersion() + " does not support chunk encoding"); } } else { addRequestHeader("Content-Length", String.valueOf(len)); } } }
Example #11
Source File: HttpMethodBaseExecuteMethodInterceptor.java From pinpoint with Apache License 2.0 | 6 votes |
private String getHost(HttpMethod httpMethod, HttpConnection httpConnection) { try { final URI uri = httpMethod.getURI(); // if uri have schema if (uri.isAbsoluteURI()) { return HttpClient3RequestWrapper.getEndpoint(uri.getHost(), uri.getPort()); } if (httpConnection != null) { final String host = httpConnection.getHost(); final int port = HttpClient3RequestWrapper.getPort(httpConnection); return HttpClient3RequestWrapper.getEndpoint(host, port); } } catch (Exception e) { if (isDebug) { logger.debug("Failed to get host. httpMethod={}", httpMethod, e); } } return null; }
Example #12
Source File: OptionsMethod.java From knopflerfish.org with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * <p> * This implementation will parse the <tt>Allow</tt> header to obtain * the set of methods supported by the resource identified by the Request-URI. * </p> * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @see #readResponse * @see #readResponseHeaders * @since 2.0 */ protected void processResponseHeaders(HttpState state, HttpConnection conn) { LOG.trace("enter OptionsMethod.processResponseHeaders(HttpState, HttpConnection)"); Header allowHeader = getResponseHeader("allow"); if (allowHeader != null) { String allowHeaderValue = allowHeader.getValue(); StringTokenizer tokenizer = new StringTokenizer(allowHeaderValue, ","); while (tokenizer.hasMoreElements()) { String methodAllowed = tokenizer.nextToken().trim().toUpperCase(); methodsAllowed.addElement(methodAllowed); } } }
Example #13
Source File: IdleConnectionHandler.java From knopflerfish.org with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Registers the given connection with this handler. The connection will be held until * {@link #remove(HttpConnection)} or {@link #closeIdleConnections(long)} is called. * * @param connection the connection to add * * @see #remove(HttpConnection) */ public void add(HttpConnection connection) { Long timeAdded = new Long(System.currentTimeMillis()); if (LOG.isDebugEnabled()) { LOG.debug("Adding connection at: " + timeAdded); } connectionToAdded.put(connection, timeAdded); }
Example #14
Source File: ExchangeDavMethod.java From davmail with GNU General Public License v2.0 | 5 votes |
@Override protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) { Header contentTypeHeader = getResponseHeader("Content-Type"); if (contentTypeHeader != null && "text/xml".equals(contentTypeHeader.getValue())) { responses = new ArrayList<>(); XMLStreamReader reader; try { reader = XMLStreamUtil.createXMLStreamReader(new FilterInputStream(getResponseBodyAsStream()) { final byte[] lastbytes = new byte[3]; @Override public int read(byte[] bytes, int off, int len) throws IOException { int count = in.read(bytes, off, len); // patch invalid element name for (int i = 0; i < count; i++) { byte currentByte = bytes[off + i]; if ((lastbytes[0] == '<') && (currentByte >= '0' && currentByte <= '9')) { // move invalid first tag char to valid range bytes[off + i] = (byte) (currentByte + 49); } lastbytes[0] = lastbytes[1]; lastbytes[1] = lastbytes[2]; lastbytes[2] = currentByte; } return count; } }); while (reader.hasNext()) { reader.next(); if (XMLStreamUtil.isStartTag(reader, "response")) { handleResponse(reader); } } } catch (IOException | XMLStreamException e) { LOGGER.error("Error while parsing soap response: " + e, e); } } }
Example #15
Source File: HttpClient3RequestWrapper.java From pinpoint with Apache License 2.0 | 5 votes |
public static int getPort(final HttpConnection httpConnection) { if (httpConnection == null) { return SKIP_DEFAULT_PORT; } final int port = httpConnection.getPort(); final Protocol protocol = httpConnection.getProtocol(); // if port is default port number. if (protocol != null && port == protocol.getDefaultPort()) { // skip return SKIP_DEFAULT_PORT; } return port; }
Example #16
Source File: HttpMethodBaseExecuteMethodInterceptor.java From pinpoint with Apache License 2.0 | 5 votes |
@Override public void after(Object target, Object[] args, Object result, Throwable throwable) { if (isDebug) { logger.afterInterceptor(target, args); } final Trace trace = traceContext.currentTraceObject(); if (trace == null) { return; } try { final SpanEventRecorder recorder = trace.currentSpanEventRecorder(); recorder.recordApi(descriptor); recorder.recordException(throwable); if (target instanceof HttpMethod) { final HttpMethod httpMethod = (HttpMethod) target; final HttpConnection httpConnection = getHttpConnection(args); final ClientRequestWrapper requestWrapper = new HttpClient3RequestWrapper(httpMethod, httpConnection); this.clientRequestRecorder.record(recorder, requestWrapper, throwable); this.cookieRecorder.record(recorder, httpMethod, throwable); this.entityRecorder.record(recorder, httpMethod, throwable); } if (result != null) { recorder.recordAttribute(AnnotationKey.HTTP_STATUS_CODE, result); } final HttpClient3CallContext callContext = getAndCleanAttachment(); if (callContext != null) { recordIo(recorder, callContext); } } finally { trace.traceBlockEnd(); } }
Example #17
Source File: HttpRecorderPostMethod.java From webarchive-commons with Apache License 2.0 | 5 votes |
public int execute(HttpState state, HttpConnection conn) throws HttpException, IOException { // Save off the connection so we can close it on our way out in case // httpclient fails to (We're not supposed to have access to the // underlying connection object; am only violating contract because // see cases where httpclient is skipping out w/o cleaning up // after itself). this.httpRecorderMethod.setConnection(conn); return super.execute(state, conn); }
Example #18
Source File: SingleHttpConnectionManager.java From webarchive-commons with Apache License 2.0 | 5 votes |
public HttpConnection getConnectionWithTimeout( HostConfiguration hostConfiguration, long timeout) { HttpConnection conn = new HttpConnection(hostConfiguration); conn.setHttpConnectionManager(this); conn.getParams().setDefaults(this.getParams()); return conn; }
Example #19
Source File: SingleHttpConnectionManager.java From webarchive-commons with Apache License 2.0 | 5 votes |
protected static void finishLast(HttpConnection conn) { // copied from superclass because it wasn't made available to subclasses InputStream lastResponse = conn.getLastResponseInputStream(); if (lastResponse != null) { conn.setLastResponseInputStream(null); try { lastResponse.close(); } catch (IOException ioe) { //FIXME: badness - close to force reconnect. conn.close(); } } }
Example #20
Source File: ThreadLocalHttpConnectionManager.java From webarchive-commons with Apache License 2.0 | 5 votes |
/** * @see HttpConnectionManager#releaseConnection(org.apache.commons.httpclient.HttpConnection) */ public void releaseConnection(final HttpConnection conn) { final ConnectionInfo ci = getConnectionInfo(); HttpConnection httpConnection = ci.conn; if(conn != httpConnection) { throw new IllegalStateException( "Unexpected release of an unknown connection."); } finishLastResponse(httpConnection); // track the time the connection was made idle ci.idleStartTime = System.currentTimeMillis(); }
Example #21
Source File: HttpRecorderMethod.java From webarchive-commons with Apache License 2.0 | 5 votes |
public void markContentBegin(HttpConnection c) { if (c != this.connection) { // We're checking that we're not being asked to work on // a connection that is other than the one we started // this method#execute with. throw new IllegalArgumentException("Connections differ: " + this.connection + " " + c + " " + Thread.currentThread().getName()); } this.httpRecorder.markContentBegin(); }
Example #22
Source File: HttpRecorderGetMethod.java From webarchive-commons with Apache License 2.0 | 5 votes |
public int execute(HttpState state, HttpConnection conn) throws HttpException, IOException { // Save off the connection so we can close it on our way out in case // httpclient fails to (We're not supposed to have access to the // underlying connection object; am only violating contract because // see cases where httpclient is skipping out w/o cleaning up // after itself). this.httpRecorderMethod.setConnection(conn); return super.execute(state, conn); }
Example #23
Source File: EWSMethod.java From davmail with GNU General Public License v2.0 | 5 votes |
@Override protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) { Header contentTypeHeader = getResponseHeader("Content-Type"); if (contentTypeHeader != null && "text/xml; charset=utf-8".equals(contentTypeHeader.getValue())) { try { if (DavGatewayHttpClientFacade.isGzipEncoded(this)) { processResponseStream(new GZIPInputStream(getResponseBodyAsStream())); } else { processResponseStream(getResponseBodyAsStream()); } } catch (IOException e) { LOGGER.error("Error while parsing soap response: " + e, e); } } }
Example #24
Source File: StreamedPostMethod.java From jrpip with Apache License 2.0 | 5 votes |
public void reallyWriteHeaders(HttpState state, HttpConnection conn) throws IOException { this.writeRequestLine(state, conn); this.writeRequestHeaders(state, conn); conn.writeLine(); // close head // make sure the status line and headers have been sent conn.flushRequestOutputStream(); }
Example #25
Source File: HttpAuthenticator.java From knopflerfish.org with BSD 3-Clause "New" or "Revised" License | 5 votes |
private static boolean doAuthenticateDefault( HttpMethod method, HttpConnection conn, HttpState state, boolean proxy) throws AuthenticationException { if (method == null) { throw new IllegalArgumentException("HTTP method may not be null"); } if (state == null) { throw new IllegalArgumentException("HTTP state may not be null"); } String host = null; if (conn != null) { host = proxy ? conn.getProxyHost() : conn.getHost(); } Credentials credentials = proxy ? state.getProxyCredentials(null, host) : state.getCredentials(null, host); if (credentials == null) { return false; } if (!(credentials instanceof UsernamePasswordCredentials)) { throw new InvalidCredentialsException( "Credentials cannot be used for basic authentication: " + credentials.toString()); } String auth = BasicScheme.authenticate( (UsernamePasswordCredentials) credentials, method.getParams().getCredentialCharset()); if (auth != null) { String s = proxy ? PROXY_AUTH_RESP : WWW_AUTH_RESP; Header header = new Header(s, auth, true); method.addRequestHeader(header); return true; } else { return false; } }
Example #26
Source File: HeadMethod.java From knopflerfish.org with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Overrides {@link HttpMethodBase} method to <i>not</i> read a response * body, despite the presence of a <tt>Content-Length</tt> or * <tt>Transfer-Encoding</tt> header. * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * * @see #readResponse * @see #processResponseBody * * @since 2.0 */ protected void readResponseBody(HttpState state, HttpConnection conn) throws HttpException, IOException { LOG.trace( "enter HeadMethod.readResponseBody(HttpState, HttpConnection)"); int bodyCheckTimeout = getParams().getIntParameter(HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, -1); if (bodyCheckTimeout < 0) { responseBodyConsumed(); } else { if (LOG.isDebugEnabled()) { LOG.debug("Check for non-compliant response body. Timeout in " + bodyCheckTimeout + " ms"); } boolean responseAvailable = false; try { responseAvailable = conn.isResponseAvailable(bodyCheckTimeout); } catch (IOException e) { LOG.debug("An IOException occurred while testing if a response was available," + " we will assume one is not.", e); responseAvailable = false; } if (responseAvailable) { if (getParams().isParameterTrue(HttpMethodParams.REJECT_HEAD_BODY)) { throw new ProtocolException( "Body content may not be sent in response to HTTP HEAD request"); } else { LOG.warn("Body content returned in response to HTTP HEAD"); } super.readResponseBody(state, conn); } } }
Example #27
Source File: StreamedPostMethod.java From jrpip with Apache License 2.0 | 5 votes |
public BufferedChunkedOutputStream( HttpConnection conn, HttpState state, StreamedPostMethod streamedPostMethod) throws IOException { this.streamedPostMethod = streamedPostMethod; this.state = state; this.httpConnection = conn; this.cache = new byte[2048]; this.stream = this.httpConnection.getRequestOutputStream(); }
Example #28
Source File: RestMethod.java From davmail with GNU General Public License v2.0 | 5 votes |
@Override protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) { Header contentTypeHeader = getResponseHeader("Content-Type"); if (contentTypeHeader != null && "application/json; charset=utf-8".equals(contentTypeHeader.getValue())) { try { if (DavGatewayHttpClientFacade.isGzipEncoded(this)) { processResponseStream(new GZIPInputStream(getResponseBodyAsStream())); } else { processResponseStream(getResponseBodyAsStream()); } } catch (IOException | JSONException e) { LOGGER.error("Error while parsing json response: " + e, e); } } }
Example #29
Source File: HttpRecorderPostMethod.java From webarchive-commons with Apache License 2.0 | 4 votes |
protected void readResponseBody(HttpState state, HttpConnection connection) throws IOException, HttpException { // We're about to read the body. Mark transition in http recorder. this.httpRecorderMethod.markContentBegin(connection); super.readResponseBody(state, connection); }
Example #30
Source File: ThreadLocalHttpConnectionManager.java From webarchive-commons with Apache License 2.0 | 4 votes |
public void closeConnection(final HttpConnection conn) { synchronized (connections) { connections.add(conn); } }