类org.apache.commons.httpclient.HttpConnection源码实例Demo

下面列出了怎么用org.apache.commons.httpclient.HttpConnection的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: davmail   文件: DavExchangeSession.java
/**
 * @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();
    }
}
 
源代码2 项目: jrpip   文件: StreamedPostMethod.java
@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;
    }
}
 
源代码3 项目: jrpip   文件: BufferedPostMethod.java
@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;
    }
}
 
源代码4 项目: knopflerfish.org   文件: MultipartPostMethod.java
/**
 * 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());
    }
}
 
源代码5 项目: knopflerfish.org   文件: OptionsMethod.java
/**
 * <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);
        }
    }
}
 
源代码6 项目: knopflerfish.org   文件: EntityEnclosingMethod.java
/**
 * 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));
        }
    }
}
 
源代码7 项目: knopflerfish.org   文件: ExpectContinueMethod.java
/**
 * 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");
        }
    }
}
 
源代码8 项目: knopflerfish.org   文件: IdleConnectionHandler.java
/**
 * 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();
        }
    }
}
 
源代码9 项目: pinpoint   文件: HttpClient3RequestWrapper.java
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();
}
 
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;
}
 
/**
 * 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;
    }
}
 
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;
    }
}
 
源代码13 项目: davmail   文件: EWSMethod.java
@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);
        }
    }
}
 
源代码14 项目: davmail   文件: ExchangeDavMethod.java
@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);
        }
    }
}
 
源代码15 项目: davmail   文件: RestMethod.java
@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);
        }
    }
}
 
源代码16 项目: jrpip   文件: StreamedPostMethod.java
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();
}
 
源代码17 项目: jrpip   文件: StreamedPostMethod.java
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();
}
 
源代码18 项目: knopflerfish.org   文件: HeadMethod.java
/**
 * 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);
        }
    }

}
 
源代码19 项目: knopflerfish.org   文件: HttpAuthenticator.java
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;
    }
}
 
源代码20 项目: knopflerfish.org   文件: IdleConnectionHandler.java
/**
 * 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);
}
 
源代码21 项目: pinpoint   文件: HttpClient3RequestWrapper.java
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;
}
 
@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();
    }
}
 
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);
}
 
public HttpConnection getConnectionWithTimeout(
    HostConfiguration hostConfiguration, long timeout) {

    HttpConnection conn = new HttpConnection(hostConfiguration);
    conn.setHttpConnectionManager(this);
    conn.getParams().setDefaults(this.getParams());
    return conn;
}
 
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();
        }
    }
}
 
/**
 * @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();
}
 
源代码27 项目: webarchive-commons   文件: HttpRecorderMethod.java
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();
}
 
源代码28 项目: webarchive-commons   文件: HttpRecorderGetMethod.java
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);
}
 
源代码29 项目: jrpip   文件: StreamedPostMethod.java
protected void cleanupConnection(HttpConnection conn)
{
    conn.close();
    conn.releaseConnection();
}
 
源代码30 项目: jrpip   文件: BufferedPostMethod.java
protected void cleanupConnection(HttpConnection conn)
{
    conn.close();
    conn.releaseConnection();
}
 
 类方法
 同包方法