org.apache.commons.httpclient.HttpState Java Examples

The following examples show how to use org.apache.commons.httpclient.HttpState. 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 vote down vote up
/**
 * @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: MultipartPostMethod.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #3
Source File: OptionsMethod.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * <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 #4
Source File: EntityEnclosingMethod.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #5
Source File: OAuth2Client.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public HttpClient getHttpClient() {

		String proxyUrl = System.getProperty("http.proxyHost");
		String proxyPort = System.getProperty("http.proxyPort");
		String proxyUser = System.getProperty("http.proxyUsername");
		String proxyPassword = System.getProperty("http.proxyPassword");

		HttpClient client = new HttpClient();
		if (proxyUrl != null && proxyPort != null) {
			logger.debug("Setting proxy configuration ...");
			client.getHostConfiguration().setProxy(proxyUrl, Integer.parseInt(proxyPort));
			if (proxyUser != null) {
				logger.debug("Setting proxy authentication configuration ...");
				HttpState state = new HttpState();
				state.setProxyCredentials(null, null, new UsernamePasswordCredentials(proxyUser, proxyPassword));
				client.setState(state);
			}
		} else {
			logger.debug("No proxy configuration found");
		}

		return client;
	}
 
Example #6
Source File: HttpClientTransmitterImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Test create target.
 * 
 * @throws Exception
 */
public void testSuccessfulVerifyTargetOverHttp() throws Exception
{
    //Stub HttpClient so that executeMethod returns a 200 response
    when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), 
            any(HttpState.class))).thenReturn(200);
    
    //Call verifyTarget
    transmitter.verifyTarget(target);
    
    ArgumentCaptor<HostConfiguration> hostConfig = ArgumentCaptor.forClass(HostConfiguration.class);
    ArgumentCaptor<HttpMethod> httpMethod = ArgumentCaptor.forClass(HttpMethod.class);
    ArgumentCaptor<HttpState> httpState = ArgumentCaptor.forClass(HttpState.class);
    
    verify(mockedHttpClient).executeMethod(hostConfig.capture(), httpMethod.capture(), httpState.capture());
    
    assertTrue("post method", httpMethod.getValue() instanceof PostMethod);
    assertEquals("host name", TARGET_HOST, hostConfig.getValue().getHost());
    assertEquals("port", HTTP_PORT, hostConfig.getValue().getPort());
    assertEquals("protocol", HTTP_PROTOCOL.toLowerCase(), 
            hostConfig.getValue().getProtocol().getScheme().toLowerCase());
    assertEquals("path", TRANSFER_SERVICE_PATH + "/test", httpMethod.getValue().getPath());
}
 
Example #7
Source File: HttpClientTransmitterImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testSuccessfulVerifyTargetOverHttps() throws Exception
{
    
    //Stub HttpClient so that executeMethod returns a 200 response
    when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), 
            any(HttpState.class))).thenReturn(200);

    target.setEndpointProtocol(HTTPS_PROTOCOL);
    target.setEndpointPort(HTTPS_PORT);
    
    //Call verifyTarget
    transmitter.verifyTarget(target);
    
    ArgumentCaptor<HostConfiguration> hostConfig = ArgumentCaptor.forClass(HostConfiguration.class);
    ArgumentCaptor<HttpMethod> httpMethod = ArgumentCaptor.forClass(HttpMethod.class);
    ArgumentCaptor<HttpState> httpState = ArgumentCaptor.forClass(HttpState.class);
    
    verify(mockedHttpClient).executeMethod(hostConfig.capture(), httpMethod.capture(), httpState.capture());
    
    assertEquals("port", HTTPS_PORT, hostConfig.getValue().getPort());
    assertTrue("socket factory", 
            hostConfig.getValue().getProtocol().getSocketFactory() instanceof SecureProtocolSocketFactory);
    assertEquals("protocol", HTTPS_PROTOCOL.toLowerCase(), 
            hostConfig.getValue().getProtocol().getScheme().toLowerCase());
}
 
Example #8
Source File: ExpectContinueMethod.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #9
Source File: BufferedPostMethod.java    From jrpip with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: StreamedPostMethod.java    From jrpip with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: Manager.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
private void createHttpClient() {
    Protocol protocol = Protocol.getProtocol("https");
    if (protocol == null) {
        // ZAP: Dont override an existing protocol - it causes problems with ZAP
        Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        Protocol.registerProtocol("https", easyhttps);
    }
    initialState = new HttpState();

    MultiThreadedHttpConnectionManager connectionManager =
            new MultiThreadedHttpConnectionManager();
    connectionManager.getParams().setDefaultMaxConnectionsPerHost(1000);
    connectionManager.getParams().setMaxTotalConnections(1000);

    // connectionManager.set

    httpclient = new HttpClient(connectionManager);
    // httpclient.

}
 
Example #12
Source File: HttpClientWrapper.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * This is meant for system use so you should not be constructing this,
 * use the {@link HttpRESTUtils#makeReusableHttpClient(boolean, int, javax.servlet.http.Cookie[])} instead
 */
public HttpClientWrapper(HttpClient httpClient, 
        MultiThreadedHttpConnectionManager multiThreadedHttpConnectionManager,
        HttpState initialHttpState) {
    super();
    this.httpClient = httpClient;
    this.connectionManager = multiThreadedHttpConnectionManager;
    this.initialHttpState = initialHttpState;
}
 
Example #13
Source File: RORClient.java    From development with Apache License 2.0 5 votes vote down vote up
public HttpClient createHttpClient() {
	HttpClient client = new HttpClient();

	String proxyHost = System.getProperty(HTTPS_PROXY_HOST);
	String proxyPort = System.getProperty(HTTPS_PROXY_PORT);
	String proxyUser = System.getProperty(HTTPS_PROXY_USER);
	String proxyPassword = System.getProperty(HTTPS_PROXY_PASSWORD);
	int proxyPortInt = 0;

	try {
		proxyPortInt = Integer.parseInt(proxyPort);
	} catch (NumberFormatException e) {
		// ignore
	}
	if (!useProxyByPass(this.apiUrl)) {
		if (proxyHost != null && proxyPortInt > 0) {
			client.getHostConfiguration().setProxy(proxyHost, proxyPortInt);

			if (proxyUser != null && proxyUser.length() > 0
					&& proxyPassword != null && proxyPassword.length() > 0) {
				HttpState state = new HttpState();
				Credentials proxyCredentials = new UsernamePasswordCredentials(
						proxyUser, proxyPassword);
				state.setProxyCredentials(new AuthScope(proxyHost,
						proxyPortInt), proxyCredentials);
				client.setState(state);
			}
		}
	}
	return client;
}
 
Example #14
Source File: HeadMethod.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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 #15
Source File: HttpAuthenticator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #16
Source File: ExchangeDavMethod.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
@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 #17
Source File: HttpClientWrapper.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Resets the http client state between requests,
 * this is not necessarily required but might be a good idea
 */
public void resetState() {
    if (initialHttpState != null) {
        httpClient.setState(initialHttpState);
    } else {
        httpClient.setState( new HttpState() );
    }
}
 
Example #18
Source File: HttpClientWrapper.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * This is meant for system use so you should not be constructing this,
 * use the {@link HttpRESTUtils#makeReusableHttpClient(boolean, int, javax.servlet.http.Cookie[])} instead
 */
public HttpClientWrapper(HttpClient httpClient, 
        MultiThreadedHttpConnectionManager multiThreadedHttpConnectionManager,
        HttpState initialHttpState) {
    super();
    this.httpClient = httpClient;
    this.connectionManager = multiThreadedHttpConnectionManager;
    this.initialHttpState = initialHttpState;
}
 
Example #19
Source File: HttpClientWrapper.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Resets the http client state between requests,
 * this is not necessarily required but might be a good idea
 */
public void resetState() {
    if (initialHttpState != null) {
        httpClient.setState(initialHttpState);
    } else {
        httpClient.setState( new HttpState() );
    }
}
 
Example #20
Source File: CredentialsUtils.java    From httpclientAuthHelper with Apache License 2.0 5 votes vote down vote up
public static void setProxyHost(HttpClient httpClient, UsernamePasswordCredentials proxyCredentials,
                                String proxyHost, int proxyPort) {

    if (proxyHost != null && !proxyHost.isEmpty()) {
        httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (proxyCredentials != null) {
            HttpState state = new HttpState();
            state.setProxyCredentials(new AuthScope(proxyHost, proxyPort), proxyCredentials);
            httpClient.setState(state);
        }
    }
}
 
Example #21
Source File: HttpRecorderPostMethod.java    From webarchive-commons with Apache License 2.0 5 votes vote down vote up
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 #22
Source File: HttpRecorderGetMethod.java    From webarchive-commons with Apache License 2.0 5 votes vote down vote up
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: TraceeHttpClientDecorator.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public int executeMethod(HostConfiguration hostconfig, HttpMethod method, HttpState state) throws IOException, HttpException {
	preRequest(method);
	try {
		int result = delegate.executeMethod(hostconfig, method, state);
		postResponse(method);
		return result;
	} finally {
		cancel();
	}
}
 
Example #24
Source File: SsoUtil.java    From iaf with Apache License 2.0 5 votes vote down vote up
public static void addSsoCredential(HttpMethod method, HttpState state, String defaultForwardHost) {
	try {
		String name=SsoUtil.getSsoTokenName();
		String value=SsoUtil.getSsoToken();
		if (StringUtils.isEmpty(value)) {
			if (log.isDebugEnabled()) log.debug("no value for SsoCredential ["+name+"]");
		} else {
			if (log.isDebugEnabled()) log.debug("constructing SsoCredentialCookie ["+name+"]");
			Cookie ssoCookie = new Cookie();
			ssoCookie.setName(name);
		
			ssoCookie.setValue(value);
			String forwardHost;
			try {
				URI uri = method.getURI();
				forwardHost = uri.getHost();
				if (StringUtils.isEmpty(forwardHost)) {
					if (log.isDebugEnabled()) log.debug("did not find host from URI ["+uri.getURI()+"], will use default ["+defaultForwardHost+"] for SSO credential cookie");
					forwardHost=defaultForwardHost;
				}
			} catch (Throwable t) {
				log.warn("could not extract host from URI", t);
				forwardHost = defaultForwardHost;					
			}
			ssoCookie.setDomain(forwardHost);
			// path must have a value, otherwise cookie is not appended to request
			ssoCookie.setPath("/");
			if (log.isDebugEnabled()) log.debug("set SSOcookie attributes: domain ["+ssoCookie.getDomain()+"] path ["+ssoCookie.getPath()+"]");
			state.addCookie(ssoCookie);
		}
		
	} catch (Exception e) {
		log.warn("could not obtain SsoToken: "+e.getMessage());
	}
}
 
Example #25
Source File: StreamedPostMethod.java    From jrpip with Apache License 2.0 5 votes vote down vote up
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 #26
Source File: EWSMethod.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
@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 #27
Source File: RestMethod.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
@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 #28
Source File: HttpClientUtil.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
/**
  * <p>
  * 初始化HttpClient对象,同时设置转发应用的Cookie信息。
  * 将当前请求中的cookie信息(除去sessionId cookie 和 token cookie)设置到新的请求中来
  * </p>
  * @param targetAS 转发的目标应用
  * @return
  */
 public static HttpClient getHttpClient(AppServer targetAS) {
 	HttpState initialState = new HttpState();
     HttpServletRequest request = Context.getRequestContext().getRequest();
     javax.servlet.http.Cookie[] cookies = request.getCookies();
     cookies = (javax.servlet.http.Cookie[]) EasyUtils.checkNull(cookies, new javax.servlet.http.Cookie[] {});
     
     // 设置转发Cookies信息
     AppServer currentAS = Context.getApplicationContext().getCurrentAppServer();
     for (javax.servlet.http.Cookie cookie : request.getCookies()) {
         String cookieName = cookie.getName();
         if (cookieName.equals(currentAS.getSessionIdName()) 
         		|| cookieName.equals(RequestContext.USER_TOKEN)) {
             continue;
         }
         
         // 保存当前应用以外的sessionId信息的cookie一般是以其应用Code命名的,当前应用的则以JSESSIONID命名
         if (cookieName.equals(targetAS.getCode())) { 
             cookieName = targetAS.getSessionIdName();
         }
         String domain = targetAS.getDomain();
String path   = targetAS.getPath();
Cookie apacheCookie = new Cookie(domain, cookieName, cookie.getValue(), path, null, request.isSecure());
         initialState.addCookie(apacheCookie);
     }
     
     HttpClient client = getHttpClient();
     client.setState(initialState);
     
     return client;
 }
 
Example #29
Source File: Filter5HttpProxy.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 请求转向不同同服务器的其他应用
 * </p>
 * @param appServer
 * @param req
 * @param response
 * @throws IOException
 * @throws BusinessServletException
 */
private void proxy4ForeignApplication(AppServer appServer, HttpServletResponse response) throws IOException, BusinessServletException {
       HttpClient client = HttpClientUtil.getHttpClient(appServer); // 创建HttpClient对象
	HttpState httpState = client.getState();
	
	/* 设置用户令牌相关Cookie,包括一个token Cookie和一个 sessionId Cookie */
       boolean isSecure = Context.getRequestContext().isSecure(); //是否https请求
       String currentAppCode = Context.getApplicationContext().getCurrentAppCode(); //当前应用code
       String domain = appServer.getDomain();
       String path   = appServer.getPath(); 
       if (Context.isOnline()) {
           httpState.addCookie(new Cookie(domain, RequestContext.USER_TOKEN, Context.getToken(), path, null, isSecure)); //token = ****************
       }
       if (Environment.getSessionId() != null) {
           httpState.addCookie(new Cookie(domain, currentAppCode, Environment.getSessionId(), path, null, isSecure)); // TSS = JSessionId
       }
	
	HttpMethod httpMethod = HttpClientUtil.getHttpMethod(appServer); // 创建HttpPost对象(等价于一个Post Http Request)
	try {
		// 请求
           int statusCode = client.executeMethod(httpMethod);
		if (statusCode == HttpStatus.SC_OK) {
			// 转发返回信息
			transmitResponse(appServer, response, client, httpMethod);
		} 
		else if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
				|| (statusCode == HttpStatus.SC_MOVED_PERMANENTLY)
				|| (statusCode == HttpStatus.SC_SEE_OTHER)
				|| (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
		    
			dealWithRedirect(appServer, response, client, httpMethod);
		} 
		
	} finally {
		httpMethod.releaseConnection();
	}
}
 
Example #30
Source File: HttpClientTransmitterImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testHttpsVerifyTargetWithCustomSocketFactory() throws Exception
{
    //Override the default SSL socket factory with our own custom one...
    CustomSocketFactory socketFactory = new CustomSocketFactory();
    transmitter.setHttpsSocketFactory(socketFactory);
    
    target.setEndpointProtocol(HTTPS_PROTOCOL);
    target.setEndpointPort(HTTPS_PORT);
    
    //Stub HttpClient so that executeMethod returns a 200 response
    when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class), 
            any(HttpState.class))).thenReturn(200);

    //Call verifyTarget
    transmitter.verifyTarget(target);
    
    ArgumentCaptor<HostConfiguration> hostConfig = ArgumentCaptor.forClass(HostConfiguration.class);
    ArgumentCaptor<HttpMethod> httpMethod = ArgumentCaptor.forClass(HttpMethod.class);
    ArgumentCaptor<HttpState> httpState = ArgumentCaptor.forClass(HttpState.class);
    
    verify(mockedHttpClient).executeMethod(hostConfig.capture(), httpMethod.capture(), httpState.capture());
    
    assertEquals("port", HTTPS_PORT, hostConfig.getValue().getPort());
    //test that the socket factory passed to HttpClient is our custom one (intentional use of '==')
    assertTrue("socket factory", hostConfig.getValue().getProtocol().getSocketFactory() == socketFactory);
    assertEquals("protocol", HTTPS_PROTOCOL.toLowerCase(), 
            hostConfig.getValue().getProtocol().getScheme().toLowerCase());
}