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

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

Introduction

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

Prototype

public abstract void setRequestHeader(String paramString1, String paramString2);

Source Link

Usage

From source file:com.cordys.coe.ac.httpconnector.impl.StandardRequestHandler.java

private void setRequestHeaders(HttpMethod httpMethod) {
    for (RequestHeader requestHeader : requestHeadersArray) {
        httpMethod.setRequestHeader(requestHeader.name, String.valueOf(requestHeader.value));
    }/*from  ww w .ja  va2 s .  co  m*/
}

From source file:com.zimbra.cs.dav.client.WebDavClient.java

protected HttpMethod executeMethod(HttpMethod m, Depth d, String bodyForLogging) throws IOException {
    HttpMethodParams p = m.getParams();/*from  w w w.j  a  va2  s . c o m*/
    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;
}

From source file:com.baidu.oped.apm.profiler.modifier.connector.httpclient3.interceptor.ExecuteInterceptor.java

@Override
public void before(Object target, Object[] args) {
    if (isDebug) {
        logger.beforeInterceptor(target, args);
    }/*from  w w w.  j  av  a 2  s . c om*/

    final Trace trace = traceContext.currentRawTraceObject();

    if (trace == null) {
        return;
    }

    final HttpMethod httpMethod = getHttpMethod(args);
    final boolean sampling = trace.canSampled();

    if (!sampling) {
        if (isDebug) {
            logger.debug("set Sampling flag=false");
        }
        if (httpMethod != null) {
            httpMethod.setRequestHeader(Header.HTTP_SAMPLED.toString(), SamplingFlagUtils.SAMPLING_RATE_FALSE);
        }

        return;
    }

    trace.traceBlockBegin();
    trace.markBeforeTime();
    TraceId nextId = trace.getTraceId().getNextTraceId();
    trace.recordNextSpanId(nextId.getSpanId());
    trace.recordServiceType(ServiceType.HTTP_CLIENT);

    if (httpMethod != null) {
        httpMethod.setRequestHeader(Header.HTTP_TRACE_ID.toString(), nextId.getTransactionId());
        httpMethod.setRequestHeader(Header.HTTP_SPAN_ID.toString(), String.valueOf(nextId.getSpanId()));
        httpMethod.setRequestHeader(Header.HTTP_PARENT_SPAN_ID.toString(),
                String.valueOf(nextId.getParentSpanId()));
        httpMethod.setRequestHeader(Header.HTTP_FLAGS.toString(), String.valueOf(nextId.getFlags()));
        httpMethod.setRequestHeader(Header.HTTP_PARENT_APPLICATION_NAME.toString(),
                traceContext.getApplicationName());
        httpMethod.setRequestHeader(Header.HTTP_PARENT_APPLICATION_TYPE.toString(),
                Short.toString(traceContext.getServerTypeCode()));
    }
}

From source file:com.navercorp.pinpoint.plugin.httpclient3.interceptor.ExecuteInterceptor.java

@Override
public void before(Object target, Object[] args) {
    if (isDebug) {
        logger.beforeInterceptor(target, args);
    }//from w w  w .j ava 2s  .co  m

    final Trace trace = traceContext.currentRawTraceObject();
    if (trace == null) {
        return;
    }

    final HttpMethod httpMethod = getHttpMethod(args);
    final boolean sampling = trace.canSampled();
    if (!sampling) {
        if (isDebug) {
            logger.debug("set Sampling flag=false");
        }
        if (httpMethod != null) {
            httpMethod.setRequestHeader(Header.HTTP_SAMPLED.toString(), SamplingFlagUtils.SAMPLING_RATE_FALSE);
        }

        return;
    }

    trace.traceBlockBegin();
    trace.markBeforeTime();

    TraceId nextId = trace.getTraceId().getNextTraceId();
    trace.recordNextSpanId(nextId.getSpanId());
    trace.recordServiceType(ServiceType.HTTP_CLIENT);

    if (httpMethod != null) {
        httpMethod.setRequestHeader(Header.HTTP_TRACE_ID.toString(), nextId.getTransactionId());
        httpMethod.setRequestHeader(Header.HTTP_SPAN_ID.toString(), String.valueOf(nextId.getSpanId()));
        httpMethod.setRequestHeader(Header.HTTP_PARENT_SPAN_ID.toString(),
                String.valueOf(nextId.getParentSpanId()));
        httpMethod.setRequestHeader(Header.HTTP_FLAGS.toString(), String.valueOf(nextId.getFlags()));
        httpMethod.setRequestHeader(Header.HTTP_PARENT_APPLICATION_NAME.toString(),
                traceContext.getApplicationName());
        httpMethod.setRequestHeader(Header.HTTP_PARENT_APPLICATION_TYPE.toString(),
                Short.toString(traceContext.getServerTypeCode()));
        final String host = getHost(httpMethod);
        if (host != null) {
            httpMethod.setRequestHeader(Header.HTTP_HOST.toString(), host);
        }
    }
}

From source file:edu.caltech.ipac.firefly.server.network.HttpServices.java

/**
 * Execute the given HTTP method with the given parameters.
 * @param method    the function or method to perform
 * @param cookies   optional, sent with request if present.
 * @return  true is the request was successfully received, understood, and accepted (code 2xx).
 *///from   w ww.j a v a 2s .  co m
public static boolean executeMethod(HttpMethod method, String userId, String password,
        Map<String, String> cookies) {
    try {
        if (!StringUtils.isEmpty(userId)) {
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userId, password);
            httpClient.getState().setCredentials(AuthScope.ANY, credentials);
        } else {
            // check to see if the userId and password is in the url
            userId = URLDownload.getUserFromUrl(method.toString());
            if (userId != null) {
                password = URLDownload.getPasswordFromUrl(method.toString());
                UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userId, password);
                httpClient.getState().setCredentials(AuthScope.ANY, credentials);
            }
        }

        if (cookies != null) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : cookies.entrySet()) {
                if (sb.length() > 0)
                    sb.append("; ");
                sb.append(entry.getKey());
                sb.append("=");
                sb.append(entry.getValue());
            }
            if (sb.length() > 0) {
                method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
                method.setRequestHeader("Cookie", sb.toString());
            }
        }

        int status = httpClient.executeMethod(method);
        boolean isSuccess = status >= 200 && status < 300;
        String reqDesc = "URL:" + method.getURI();
        if (isSuccess) {
            LOG.info(reqDesc);
        } else {
            reqDesc = reqDesc + "\nREQUEST HEADERS: "
                    + CollectionUtil.toString(method.getRequestHeaders()).replaceAll("\\r|\\n", "")
                    + "\nPARAMETERS:\n " + getDesc(method.getParams()) + "\nRESPONSE HEADERS: "
                    + CollectionUtil.toString(method.getResponseHeaders()).replaceAll("\\r|\\n", "");

            LOG.error("HTTP request failed with status:" + status + "\n" + reqDesc);
        }
        return isSuccess;
    } catch (Exception e) {
        LOG.error(e, "Unable to connect to:" + method.toString());
    }
    return false;
}

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

/** Prepares method headers.
 *
 * Modifies the given method by inserting, when defined:
 *  - Referer/* ww w  .j a va 2s .c  om*/
 *  - 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:com.zimbra.cs.fb.ExchangeFreeBusyProvider.java

private int sendRequest(HttpMethod method, ServerInfo info) throws IOException {
    method.setDoAuthentication(true);//  ww  w  .  ja v a 2  s .c  om
    method.setRequestHeader(HEADER_USER_AGENT, USER_AGENT);
    HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
    HttpProxyUtil.configureProxy(client);
    switch (info.scheme) {
    case basic:
        basicAuth(client, info);
        break;
    case form:
        formAuth(client, info);
        break;
    }
    return HttpClientUtil.executeMethod(client, method);
}

From source file:com.intuit.tank.httpclient3.TankHttpClient3.java

/**
 * Set all the header keys/*from  ww  w  .java  2 s. com*/
 * 
 * @param connection
 */
@SuppressWarnings("rawtypes")
private void setHeaders(BaseRequest request, HttpMethod method, HashMap<String, String> headerInformation) {
    try {
        Set set = headerInformation.entrySet();
        Iterator iter = set.iterator();

        while (iter.hasNext()) {
            Map.Entry mapEntry = (Map.Entry) iter.next();
            method.setRequestHeader((String) mapEntry.getKey(), (String) mapEntry.getValue());
        }
    } catch (Exception ex) {
        logger.warn(request.getLogUtil().getLogMessage("Unable to set header: " + ex.getMessage(),
                LogEventType.System));
    }
}

From source file:com.yahoo.flowetl.services.http.BaseHttpGenerator.java

/**
 * Applies any common properties to the http method based on properties of
 * the http params given./*from   w w  w  . j  a va  2 s .c  o  m*/
 */
protected void applyCommonProperties(HttpParams in, HttpMethod toCall) {
    // common ops
    if (in.headers != null) {
        for (Entry<String, String> e : in.headers.entrySet()) {
            toCall.addRequestHeader(e.getKey(), e.getValue());
        }
    }
    // we handle our own retries
    toCall.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));
    if (StringUtils.isBlank(in.userAgent) == false && toCall.getRequestHeader(USER_AGENT_HEADER) == null) {
        toCall.setRequestHeader(USER_AGENT_HEADER, in.userAgent);
    } else if (toCall.getRequestHeader(USER_AGENT_HEADER) == null) {
        toCall.setRequestHeader(USER_AGENT_HEADER, userAgent);
    }
}

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

/** 
 * POST//from   w  w w .  j  a va  2s  .com
 * 
 * Posts the parametersBody
 * @throws RailsAppException 
 */
protected byte[] post(NameValuePair[] parametersBody, Map<String, Object[]> files)
        throws HttpException, IOException, RailsAppException {
    // Response body from the web server
    byte[] responseBody = null;
    statusCode = -1;

    List<File> tempFiles = null;

    HttpClient client = preparedClient();

    // Create a method instance.
    PostMethod method = new PostMethod(requestURL.toString());
    HttpMethod _method = (HttpMethod) method;

    String action = "POST action request URL: " + requestURL.toString();
    if (ajax) {
        log.debug("Ajax " + action);
        _method.setRequestHeader("X_REQUESTED_WITH", "XMLHttpRequest");
        _method.setRequestHeader("ACCEPT", "text/javascript, text/html, application/xml, text/xml, */*");
        _method.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
    } else
        log.debug(action);

    // finalize method
    method = (PostMethod) prepareMethodHeaders(_method);

    if (files != null && files.size() > 0) {

        tempFiles = new ArrayList<File>();
        createMultipartRequest(parametersBody, files, method, tempFiles);

    } else {
        // Array of parameters may not be null, so init empty NameValuePair[]
        if (parametersBody == null) {
            parametersBody = new NameValuePair[0];
        }
        method.setRequestBody(parametersBody);

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

    try {
        // Execute the method.
        statusCode = client.executeMethod(method);

        if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY) || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY)
                || (statusCode == HttpStatus.SC_SEE_OTHER)
                || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {

            // get Location
            String location = ((Header) method.getResponseHeader("Location")).getValue();
            requestURL = new URL(location);
            log.debug("POST status code: " + method.getStatusLine());
            log.debug("Redirect to location: " + location);

            // server may add another cookie before redirect..
            cookies = client.getState().getCookies();

            // Note that this GET overwrites the previous POST method,
            // so it should set statusCode and cookies correctly.
            responseBody = get();

        } else {
            // the original POST method was OK, pass
            // No more redirects! Response should be 200 OK
            if (statusCode != HttpStatus.SC_OK) {
                String errorMessage = "Method failed: " + method.getStatusLine();
                log.error(errorMessage);
                throw new RailsAppException(errorMessage, new String(method.getResponseBody()));

            } else {
                log.debug("POST status code: " + method.getStatusLine());
            }

            // Read the response body.
            responseBody = method.getResponseBody();

            // Keep the headers for future usage (render or resource phase)
            configureHeader(method.getResponseHeaders());

            // Get session cookies
            cookies = client.getState().getCookies();
        }

    } finally {
        // Release the connection
        method.releaseConnection();

        // Delete temp files
        deleteFiles(tempFiles);
    }

    return responseBody;
}