Search in sources :

Example 6 with HttpMethodParams

use of org.apache.commons.httpclient.params.HttpMethodParams in project tdi-studio-se by Talend.

the class HttpMethodBase method recycle.

/**
     * Recycles the HTTP method so that it can be used again.
     * Note that all of the instance variables will be reset
     * once this method has been called. This method will also
     * release the connection being used by this HTTP method.
     * 
     * @see #releaseConnection()
     * 
     * @deprecated no longer supported and will be removed in the future
     *             version of HttpClient
     */
public void recycle() {
    LOG.trace("enter HttpMethodBase.recycle()");
    releaseConnection();
    path = null;
    followRedirects = false;
    doAuthentication = true;
    queryString = null;
    getRequestHeaderGroup().clear();
    getResponseHeaderGroup().clear();
    getResponseTrailerHeaderGroup().clear();
    statusLine = null;
    effectiveVersion = null;
    aborted = false;
    used = false;
    params = new HttpMethodParams();
    responseBody = null;
    recoverableExceptionCount = 0;
    connectionCloseForced = false;
    hostAuthState.invalidate();
    proxyAuthState.invalidate();
    cookiespec = null;
    requestSent = false;
}
Also used : HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams)

Example 7 with HttpMethodParams

use of org.apache.commons.httpclient.params.HttpMethodParams in project zm-mailbox by Zimbra.

the class SoapHttpTransport method invoke.

public Element invoke(Element document, boolean raw, boolean noSession, String requestedAccountId, String changeToken, String tokenType, ResponseHandler respHandler) throws IOException, HttpException, ServiceException {
    PostMethod method = null;
    try {
        // Assemble post method.  Append document name, so that the request
        // type is written to the access log.
        String uri, query;
        int i = mUri.indexOf('?');
        if (i >= 0) {
            uri = mUri.substring(0, i);
            query = mUri.substring(i);
        } else {
            uri = mUri;
            query = "";
        }
        if (!uri.endsWith("/"))
            uri += '/';
        uri += getDocumentName(document);
        method = new PostMethod(uri + query);
        // Set user agent if it's specified.
        String agentName = getUserAgentName();
        if (agentName != null) {
            String agentVersion = getUserAgentVersion();
            if (agentVersion != null)
                agentName += " " + agentVersion;
            method.setRequestHeader(new Header("User-Agent", agentName));
        }
        // the content-type charset will determine encoding used
        // when we set the request body
        method.setRequestHeader("Content-Type", getRequestProtocol().getContentType());
        if (getClientIp() != null) {
            method.setRequestHeader(RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            if (ZimbraLog.misc.isDebugEnabled()) {
                ZimbraLog.misc.debug("set remote IP header [%s] to [%s]", RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            }
        }
        Element soapReq = generateSoapMessage(document, raw, noSession, requestedAccountId, changeToken, tokenType);
        String soapMessage = SoapProtocol.toString(soapReq, getPrettyPrint());
        HttpMethodParams params = method.getParams();
        method.setRequestEntity(new StringRequestEntity(soapMessage, null, "UTF-8"));
        if (getRequestProtocol().hasSOAPActionHeader())
            method.setRequestHeader("SOAPAction", mUri);
        if (mCustomHeaders != null) {
            for (Map.Entry<String, String> entry : mCustomHeaders.entrySet()) method.setRequestHeader(entry.getKey(), entry.getValue());
        }
        String host = method.getURI().getHost();
        HttpState state = HttpClientUtil.newHttpState(getAuthToken(), host, this.isAdmin());
        String trustedToken = getTrustedToken();
        if (trustedToken != null) {
            state.addCookie(new Cookie(host, ZimbraCookie.COOKIE_ZM_TRUST_TOKEN, trustedToken, "/", null, false));
        }
        params.setCookiePolicy(state.getCookies().length == 0 ? CookiePolicy.IGNORE_COOKIES : CookiePolicy.BROWSER_COMPATIBILITY);
        params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(mRetryCount - 1, true));
        params.setSoTimeout(mTimeout);
        params.setVersion(HttpVersion.HTTP_1_1);
        method.setRequestHeader("Connection", mKeepAlive ? "Keep-alive" : "Close");
        if (mHostConfig != null && mHostConfig.getUsername() != null && mHostConfig.getPassword() != null) {
            state.setProxyCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(mHostConfig.getUsername(), mHostConfig.getPassword()));
        }
        if (mHttpDebugListener != null) {
            mHttpDebugListener.sendSoapMessage(method, soapReq, state);
        }
        int responseCode = mClient.executeMethod(mHostConfig, method, state);
        //   real server issues will probably be "503" or "404"
        if (responseCode != HttpServletResponse.SC_OK && responseCode != HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
            throw ServiceException.PROXY_ERROR(method.getStatusLine().toString(), uri);
        // Read the response body.  Use the stream API instead of the byte[]
        // version to avoid HTTPClient whining about a large response.
        InputStreamReader reader = new InputStreamReader(method.getResponseBodyAsStream(), SoapProtocol.getCharset());
        String responseStr = "";
        try {
            if (respHandler != null) {
                respHandler.process(reader);
                return null;
            } else {
                responseStr = ByteUtil.getContent(reader, (int) method.getResponseContentLength(), false);
                Element soapResp = parseSoapResponse(responseStr, raw);
                if (mHttpDebugListener != null) {
                    mHttpDebugListener.receiveSoapMessage(method, soapResp);
                }
                return soapResp;
            }
        } catch (SoapFaultException x) {
            // attach request/response to the exception and rethrow
            x.setFaultRequest(soapMessage);
            x.setFaultResponse(responseStr.substring(0, Math.min(10240, responseStr.length())));
            throw x;
        }
    } finally {
        // Release the connection to the connection manager
        if (method != null)
            method.releaseConnection();
        // exits.  Leave it here anyway.
        if (!mKeepAlive)
            mClient.getHttpConnectionManager().closeIdleConnections(0);
    }
}
Also used : ZimbraCookie(com.zimbra.common.util.ZimbraCookie) Cookie(org.apache.commons.httpclient.Cookie) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) InputStreamReader(java.io.InputStreamReader) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpState(org.apache.commons.httpclient.HttpState) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Header(org.apache.commons.httpclient.Header) AuthScope(org.apache.commons.httpclient.auth.AuthScope) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with HttpMethodParams

use of org.apache.commons.httpclient.params.HttpMethodParams in project zm-mailbox by Zimbra.

the class WebDavClient method executeMethod.

protected HttpMethod executeMethod(HttpMethod m, Depth d, String bodyForLogging) throws IOException {
    HttpMethodParams p = m.getParams();
    if (p != null)
        p.setCredentialCharset("UTF-8");
    m.setDoAuthentication(true);
    m.setRequestHeader("User-Agent", mUserAgent);
    String depth = "0";
    switch(d) {
        case one:
            depth = "1";
            break;
        case infinity:
            depth = "infinity";
            break;
        case zero:
            break;
        default:
            break;
    }
    m.setRequestHeader("Depth", depth);
    logRequestInfo(m, bodyForLogging);
    HttpClientUtil.executeMethod(mClient, m);
    logResponseInfo(m);
    return m;
}
Also used : HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams)

Example 9 with HttpMethodParams

use of org.apache.commons.httpclient.params.HttpMethodParams in project zm-mailbox by Zimbra.

the class TestProvIDN method testBasicAuth.

@Test
public void testBasicAuth() throws Exception {
    Names.IDNName domainName = new Names.IDNName(makeTestDomainName("basicAuthTest."));
    Domain domain = createDomain(domainName.uName(), domainName.uName());
    Names.IDNName acctName = new Names.IDNName("acct", domainName.uName());
    Account acct = (Account) createTest(EntryType.ACCOUNT, NameType.UNAME, acctName);
    HttpState initialState = new HttpState();
    /*
        Cookie authCookie = new Cookie(restURL.getURL().getHost(), "ZM_AUTH_TOKEN", mAuthToken, "/", null, false);
        Cookie sessionCookie = new Cookie(restURL.getURL().getHost(), "JSESSIONID", mSessionId, "/zimbra", null, false);
        initialState.addCookie(authCookie);
        initialState.addCookie(sessionCookie);
        */
    String guestName = acct.getUnicodeName();
    String guestPassword = "test123";
    Credentials loginCredentials = new UsernamePasswordCredentials(guestName, guestPassword);
    initialState.setCredentials(AuthScope.ANY, loginCredentials);
    HttpClient client = new HttpClient();
    client.setState(initialState);
    String url = UserServlet.getRestUrl(acct) + "/Calendar";
    System.out.println("REST URL: " + url);
    HttpMethod method = new GetMethod(url);
    HttpMethodParams methodParams = method.getParams();
    methodParams.setCredentialCharset("UTF-8");
    try {
        int respCode = HttpClientUtil.executeMethod(client, method);
        if (respCode != HttpStatus.SC_OK) {
            System.out.println("failed, respCode=" + respCode);
        } else {
            boolean chunked = false;
            boolean textContent = false;
        /*
                 System.out.println("Headers:");
                 System.out.println("--------");
                 for (Header header : method.getRequestHeaders()) {
                     System.out.print("    " + header.toString());
                 }
                 System.out.println();
                 
                 System.out.println("Body:");
                 System.out.println("-----");
                 String respBody = method.getResponseBodyAsString();
                 System.out.println(respBody);
                 */
        }
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}
Also used : Account(com.zimbra.cs.account.Account) HttpState(org.apache.commons.httpclient.HttpState) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Names(com.zimbra.qa.unittest.prov.Names) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) Domain(com.zimbra.cs.account.Domain) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 10 with HttpMethodParams

use of org.apache.commons.httpclient.params.HttpMethodParams in project pinot by linkedin.

the class ServerSegmentCompletionProtocolHandler method doHttp.

private SegmentCompletionProtocol.Response doHttp(SegmentCompletionProtocol.Request request, Part[] parts) {
    SegmentCompletionProtocol.Response response = SegmentCompletionProtocol.RESP_NOT_SENT;
    HttpClient httpClient = new HttpClient();
    ControllerLeaderLocator leaderLocator = ControllerLeaderLocator.getInstance();
    final String leaderAddress = leaderLocator.getControllerLeader();
    if (leaderAddress == null) {
        LOGGER.error("No leader found {}", this.toString());
        return SegmentCompletionProtocol.RESP_NOT_LEADER;
    }
    final String url = request.getUrl(leaderAddress);
    HttpMethodBase method;
    if (parts != null) {
        PostMethod postMethod = new PostMethod(url);
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams()));
        method = postMethod;
    } else {
        method = new GetMethod(url);
    }
    LOGGER.info("Sending request {} for {}", url, this.toString());
    try {
        int responseCode = httpClient.executeMethod(method);
        if (responseCode >= 300) {
            LOGGER.error("Bad controller response code {} for {}", responseCode, this.toString());
            return response;
        } else {
            response = new SegmentCompletionProtocol.Response(method.getResponseBodyAsString());
            LOGGER.info("Controller response {} for {}", response.toJsonString(), this.toString());
            if (response.getStatus().equals(SegmentCompletionProtocol.ControllerResponseStatus.NOT_LEADER)) {
                leaderLocator.refreshControllerLeader();
            }
            return response;
        }
    } catch (IOException e) {
        LOGGER.error("IOException {}", this.toString(), e);
        leaderLocator.refreshControllerLeader();
        return response;
    }
}
Also used : SegmentCompletionProtocol(com.linkedin.pinot.common.protocols.SegmentCompletionProtocol) HttpMethodBase(org.apache.commons.httpclient.HttpMethodBase) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) IOException(java.io.IOException) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)

Aggregations

HttpMethodParams (org.apache.commons.httpclient.params.HttpMethodParams)16 IOException (java.io.IOException)5 MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)5 HttpMethod (org.apache.commons.httpclient.HttpMethod)4 PostMethod (org.apache.commons.httpclient.methods.PostMethod)4 Part (org.apache.commons.httpclient.methods.multipart.Part)4 HttpClient (org.apache.commons.httpclient.HttpClient)3 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)3 EntityEnclosingMethod (org.apache.commons.httpclient.methods.EntityEnclosingMethod)3 GetMethod (org.apache.commons.httpclient.methods.GetMethod)3 FilePart (org.apache.commons.httpclient.methods.multipart.FilePart)3 StringPart (org.apache.commons.httpclient.methods.multipart.StringPart)3 BufferedInputStream (java.io.BufferedInputStream)2 File (java.io.File)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Pattern (java.util.regex.Pattern)2 DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)2 Header (org.apache.commons.httpclient.Header)2 HttpException (org.apache.commons.httpclient.HttpException)2