Example usage for org.apache.commons.httpclient HttpMethod getParams

List of usage examples for org.apache.commons.httpclient HttpMethod getParams

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getParams.

Prototype

public abstract HttpMethodParams getParams();

Source Link

Usage

From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java

public SaxonDocument delete(String id)
        throws UnsupportedEncodingException, IOException, SaxonApiException, Exception {
    HttpClient client = new HttpClient();
    HttpMethod method;

    String urlStr = this.solrHost + "/update?stream.body="
            + URLEncoder.encode("<delete><query>id:" + id + "</query></delete>") + "&commit=true";

    Log.debug("The " + id + " item is going to be deleted");
    // Create a method instance.
    method = new GetMethod(urlStr);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Execute the method.
    int statusCode = client.executeMethod(method);
    SaxonDocument solrResponse = new SaxonDocument(method.getResponseBodyAsString());
    //Log.debug(solrResponse.getXMLDocumentString());

    if (statusCode != HttpStatus.SC_OK) {
        Log.error("Method failed: " + method.getStatusLine());
        String errorMessage = (String) solrResponse.evaluatePath("//lst[@name='error']/str[@name='msg']/text()",
                XPathConstants.STRING);
        throw new Exception(errorMessage);
    }//www .  j  ava  2 s .c o m

    return solrResponse;
}

From source file:com.mobilehelix.appserver.auth.JCIFS_NTLMScheme.java

@Override
public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException {

    LOG.log(Level.FINEST, "Enter JCIFS_NTLMScheme.authenticate(Credentials, HttpMethod)");

    if (this.state == UNINITIATED) {
        throw new IllegalStateException("NTLM authentication process has not been initiated");
    }/*  ww w.j av  a 2  s . c  o m*/

    NTCredentials ntcredentials = null;
    try {
        ntcredentials = (NTCredentials) credentials;
    } catch (ClassCastException e) {
        throw new InvalidCredentialsException(
                "Credentials cannot be used for NTLM authentication: " + credentials.getClass().getName());

    }

    NTLM ntlm = new NTLM();
    ntlm.setCredentialCharset(method.getParams().getCredentialCharset());
    String response = null;
    if (this.state == INITIATED || this.state == FAILED) {
        response = ntlm.generateType1Msg(ntcredentials.getHost(), ntcredentials.getDomain());
        this.state = TYPE1_MSG_GENERATED;
    } else {
        response = ntlm.generateType3Msg(ntcredentials.getUserName(), ntcredentials.getPassword(),
                ntcredentials.getHost(), ntcredentials.getDomain(), this.ntlmchallenge);
        this.state = TYPE3_MSG_GENERATED;
    }

    return "NTLM " + response;
}

From source file:edu.utah.further.core.ws.HttpResponseTo.java

/**
 * Copy-constructor from an {@link HttpMethod}.
 * //from  w  w  w  .  jav a2 s.c o  m
 * @param method
 *            method to copy fields from
 */
public HttpResponseTo(final HttpMethod method) throws IOException {
    this.httpMethod = edu.utah.further.core.api.ws.HttpMethod.valueOf(method.getName());
    this.statusLine = method.getStatusLine();

    for (final Header header : method.getResponseHeaders()) {
        this.responseHeaders.addHeader(new Header(header.getName(), header.getValue()));
    }

    this.path = method.getPath();
    this.queryString = method.getQueryString();
    this.responseBody = method.getResponseBody();
    setParams(method.getParams());
}

From source file:ir.keloud.android.lib.common.KeloudClient.java

@Override
public int executeMethod(HttpMethod method) throws IOException, HttpException {
    try { // just to log 
        boolean customRedirectionNeeded = false;

        try {/*from   ww w  .  j  ava 2  s.  c  om*/
            method.setFollowRedirects(mFollowRedirects);
        } catch (Exception e) {
            /*
             if (mFollowRedirects) 
               Log_OC.d(TAG, "setFollowRedirects failed for " + method.getName() 
            + " method, custom redirection will be used if needed");
            */
            customRedirectionNeeded = mFollowRedirects;
        }

        // Update User Agent
        HttpParams params = method.getParams();
        String userAgent = KeloudClientManagerFactory.getUserAgent();
        params.setParameter(HttpMethodParams.USER_AGENT, userAgent);

        Log_OC.d(TAG + " #" + mInstanceNumber, "REQUEST " + method.getName() + " " + method.getPath());

        //           logCookiesAtRequest(method.getRequestHeaders(), "before");
        //           logCookiesAtState("before");

        int status = super.executeMethod(method);

        if (customRedirectionNeeded) {
            status = patchRedirection(status, method);
        }

        //           logCookiesAtRequest(method.getRequestHeaders(), "after");
        //           logCookiesAtState("after");
        //           logSetCookiesAtResponse(method.getResponseHeaders());

        return status;

    } catch (IOException e) {
        Log_OC.d(TAG + " #" + mInstanceNumber, "Exception occurred", e);
        throw e;
    }
}

From source file:com.celamanzi.liferay.portlets.rails286.OnlineClient.java

/** Prepares method headers.
 *
 * Modifies the given method by inserting, when defined:
 *  - Referer//from   w w w.j a v a 2 s . c o m
 *  - Accept-Language
 *
 * @since 0.8.0
 */
protected HttpMethod prepareMethodHeaders(HttpMethod method) {
    // Insert the HTTP Referer
    if (httpReferer != null) {
        log.debug("HTTP referer: " + httpReferer.toString());
        method.setRequestHeader("Referer", httpReferer.toString());
    } else {
        //log.debug("HTTP referer is null");
    }

    // Insert the Locale
    if (locale != null) {
        log.debug("Request's locale language: " + locale.toString());
        method.setRequestHeader("Accept-Language", locale.toString());
    } else {
        //log.debug("Locale is null");
    }

    //Correct the charset problem
    method.getParams().setContentCharset("UTF-8");

    // Provide custom retry handler
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(retries, false));

    return method;
}

From source file:net.oauth.client.httpclient3.HttpClient3.java

public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException {
    final String method = request.method;
    final String url = request.url.toExternalForm();
    final InputStream body = request.getBody();
    final boolean isDelete = DELETE.equalsIgnoreCase(method);
    final boolean isPost = POST.equalsIgnoreCase(method);
    final boolean isPut = PUT.equalsIgnoreCase(method);
    byte[] excerpt = null;
    HttpMethod httpMethod;
    if (isPost || isPut) {
        EntityEnclosingMethod entityEnclosingMethod = isPost ? new PostMethod(url) : new PutMethod(url);
        if (body != null) {
            ExcerptInputStream e = new ExcerptInputStream(body);
            String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH);
            entityEnclosingMethod.setRequestEntity((length == null) ? new InputStreamRequestEntity(e)
                    : new InputStreamRequestEntity(e, Long.parseLong(length)));
            excerpt = e.getExcerpt();/*from w w w .j  ava2  s  .c o  m*/
        }
        httpMethod = entityEnclosingMethod;
    } else if (isDelete) {
        httpMethod = new DeleteMethod(url);
    } else {
        httpMethod = new GetMethod(url);
    }
    for (Map.Entry<String, Object> p : parameters.entrySet()) {
        String name = p.getKey();
        String value = p.getValue().toString();
        if (FOLLOW_REDIRECTS.equals(name)) {
            httpMethod.setFollowRedirects(Boolean.parseBoolean(value));
        } else if (READ_TIMEOUT.equals(name)) {
            httpMethod.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, Integer.parseInt(value));
        }
    }
    for (Map.Entry<String, String> header : request.headers) {
        httpMethod.addRequestHeader(header.getKey(), header.getValue());
    }
    HttpClient client = clientPool.getHttpClient(new URL(httpMethod.getURI().toString()));
    client.executeMethod(httpMethod);
    return new HttpMethodResponse(httpMethod, excerpt, request.getContentCharset());
}

From source file:com.zenkey.net.prowser.Tab.java

/**************************************************************************
 * Writes tracing information that traces the request/response activity.
 * //from w  w  w .j  a  v a2s .c  o  m
 * @param traceLevel
 *        Indicates how much trace info to produce.
 * @param traceStream
 *        An output stream where trace statements will be written.
 * @param httpMethod
 *        The HttpMethod object of the request.
 */
private static void writeTrace(int traceLevel, PrintStream traceStream, HttpMethod httpMethod) {

    try {
        if (traceLevel >= TRACE_URI) {
            // Show trace output of the request URI
            traceStream
                    .println("-------------------------------------------------------------------------------");
            traceStream.println(httpMethod.getURI() + "\n");
        }

        if (traceLevel >= TRACE_REQUEST_RESPONSE_LINES) {
            // Show trace output of the HTTP request line
            traceStream.println(httpMethod.getName() + " " + httpMethod.getPath()
                    + (httpMethod.getQueryString() == null ? "" : "?" + httpMethod.getQueryString()) + " "
                    + httpMethod.getParams().getVersion().toString());
        }

        if (traceLevel >= TRACE_HEADERS) {
            // Show trace output of the HTTP request headers
            for (Header header : httpMethod.getRequestHeaders()) {
                traceStream.println(header.getName() + ": " + header.getValue());
            }
            // Show trace of request entity body
            if (httpMethod instanceof PostMethod) {
                NameValuePair[] parameters = ((PostMethod) httpMethod).getParameters();
                if (parameters != null) {
                    // StringBuffer parameterString = new StringBuffer();
                    // for (NameValuePair parameter : parameters) {
                    //       parameterString.append(parameter.getName() + "=" + parameter.getValue() + "&");
                    // }
                    // parameterString.deleteCharAt(parameterString.length() - 1);
                    String parameterString = new String(
                            ((ByteArrayRequestEntity) ((PostMethod) httpMethod).getRequestEntity())
                                    .getContent(),
                            "UTF-8");
                    traceStream.println("    |");
                    traceStream.println("    +-- " + parameterString);
                }
            }
            traceStream.println();
        }

        if (traceLevel >= TRACE_REQUEST_RESPONSE_LINES) {
            // Show trace output of the HTTP status line
            traceStream.println(httpMethod.getStatusLine().toString());
        }

        if (traceLevel >= TRACE_HEADERS) {
            // Show trace output of the HTTP response headers
            for (Header header : httpMethod.getResponseHeaders()) {
                traceStream.println(header.getName() + ": " + header.getValue());
            }
            traceStream.println();
        }

        if (traceLevel >= TRACE_BODY) {
            // Show trace output of the HTTP response body
            traceStream.println(httpMethod.getResponseBodyAsString());
            traceStream.println();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fedora.test.api.TestRESTAPI.java

private HttpResponse getOrDelete(String method, boolean authenticate) throws Exception {
    if (url == null || url.length() == 0) {
        throw new IllegalArgumentException("url must be a non-empty value");
    } else if (!(url.startsWith("http://") || url.startsWith("https://"))) {
        url = getBaseURL() + url;/*  ww w.  j a  v a  2s .  co  m*/
    }
    HttpMethod httpMethod = null;
    try {
        if (method.equals("GET")) {
            httpMethod = new GetMethod(url);
        } else if (method.equals("DELETE")) {
            httpMethod = new DeleteMethod(url);
        } else {
            throw new IllegalArgumentException("method must be one of GET or DELETE.");
        }

        httpMethod.setDoAuthentication(authenticate);
        httpMethod.getParams().setParameter("Connection", "Keep-Alive");
        getClient(authenticate).executeMethod(httpMethod);
        return new HttpResponse(httpMethod);
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:com.groupon.odo.Proxy.java

/**
 * Set virtual host so the server can direct the request. Value is the host header if it is set, otherwise
 * use the hostname from the original request.
 *
 * @param httpMethodProxyRequest/*from w  w  w. j  ava2 s  .  c o m*/
 * @param httpServletRequest
 */
private void processVirtualHostName(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest) {
    String virtualHostName;
    if (httpMethodProxyRequest.getRequestHeader(STRING_HOST_HEADER_NAME) != null) {
        virtualHostName = httpMethodProxyRequest.getRequestHeader(STRING_HOST_HEADER_NAME).getValue();
    } else {
        virtualHostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString());
    }
    httpMethodProxyRequest.getParams().setVirtualHost(virtualHostName);
}

From source file:com.zimbra.cs.service.UserServlet.java

private static Pair<Header[], HttpMethod> doHttpOp(ZAuthToken authToken, HttpMethod method)
        throws ServiceException {
    // create an HTTP client with the same cookies
    String url = "";
    String hostname = "";
    try {/*w ww  .j  av a  2s. co m*/
        url = method.getURI().toString();
        hostname = method.getURI().getHost();
    } catch (IOException e) {
        log.warn("can't parse target URI", e);
    }

    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    Map<String, String> cookieMap = authToken.cookieMap(false);
    if (cookieMap != null) {
        HttpState state = new HttpState();
        for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
            state.addCookie(new org.apache.commons.httpclient.Cookie(hostname, ck.getKey(), ck.getValue(), "/",
                    null, false));
        }
        client.setState(state);
        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    }

    if (method instanceof PutMethod) {
        long contentLength = ((PutMethod) method).getRequestEntity().getContentLength();
        if (contentLength > 0) {
            int timeEstimate = Math.max(10000, (int) (contentLength / 100)); // 100kbps in millis
            // cannot set connection time using our ZimbrahttpConnectionManager,
            // see comments in ZimbrahttpConnectionManager.
            // actually, length of the content to Put should not be a factor for
            // establishing a connection, only read time out matter, which we set
            // client.getHttpConnectionManager().getParams().setConnectionTimeout(timeEstimate);

            method.getParams().setSoTimeout(timeEstimate);
        }
    }

    try {
        int statusCode = HttpClientUtil.executeMethod(client, method);
        if (statusCode == HttpStatus.SC_NOT_FOUND || statusCode == HttpStatus.SC_FORBIDDEN)
            throw MailServiceException.NO_SUCH_ITEM(-1);
        else if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NO_CONTENT)
            throw ServiceException.RESOURCE_UNREACHABLE(method.getStatusText(), null,
                    new ServiceException.InternalArgument(HTTP_URL, url, ServiceException.Argument.Type.STR),
                    new ServiceException.InternalArgument(HTTP_STATUS_CODE, statusCode,
                            ServiceException.Argument.Type.NUM));

        List<Header> headers = new ArrayList<Header>(Arrays.asList(method.getResponseHeaders()));
        headers.add(new Header("X-Zimbra-Http-Status", "" + statusCode));
        return new Pair<Header[], HttpMethod>(headers.toArray(new Header[0]), method);
    } catch (HttpException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("HttpException while fetching " + url, e);
    } catch (IOException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("IOException while fetching " + url, e);
    }
}