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

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

Introduction

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

Prototype

@Override
public void setRequestHeader(String headerName, String headerValue) 

Source Link

Document

Set the specified request header, overwriting any previous value.

Usage

From source file:com.cubeia.backoffice.operator.client.OperatorServiceClientHTTP.java

private HttpMethodBase prepareMethod(HttpMethodBase method) {
    method.setRequestHeader("content-type", "application/json;charset=UTF-8;");
    // Provide custom retry handler
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(NUMBER_OF_RETRIES, false));
    return method;
}

From source file:com.cloud.utils.rest.BasicEncodedRESTValidationStrategy.java

@Override
public void executeMethod(final HttpMethodBase method, final HttpClient client, final String protocol)
        throws CloudstackRESTException, HttpException, IOException {
    if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null
            || password.isEmpty()) {/*from  ww  w . ja v a 2 s .c  o  m*/
        throw new CloudstackRESTException("Hostname/credentials are null or empty");
    }

    final String encodedCredentials = encodeCredentials();
    method.setRequestHeader("Authorization", "Basic " + encodedCredentials);
    client.executeMethod(method);
}

From source file:com.eucalyptus.blockstorage.HttpTransfer.java

/**
 * Constructs the requested method, optionally signing the request via EucaRSA-V2 signing method if signRequest=true
 * Signing the request can be done later as well by explicitly calling signEucaInternal() and passing it the output of this method.
 * That case is useful for constructing the request and then adding headers explicitly before signing takes place.
 * @param verb - The HTTP verb GET|PUT|POST|DELETE|UPDATE
 * @param addr - THe destination address for the request
 * @param eucaOperation - The EucaOperation, if any (e.g. StoreSnapshot, GetWalrusSnapshot, or other values from ObjectStorageProperties.StorageOperations)
 * @param eucaHeader - The Euca Header value, if any. This is not typically used.
 * @param signRequest - Determines if the request is signed at construction time or must be done explicitly later (boolean)
 * @return/*from w ww  . j  av  a2 s.com*/
 */
public HttpMethodBase constructHttpMethod(String verb, String addr, String eucaOperation, String eucaHeader,
        boolean signRequest) {
    String date = DateUtil.formatDate(new Date(), ISO_8601_FORMAT);
    //String date = new Date().toString();
    String httpVerb = verb;
    String addrPath = null;
    java.net.URI addrUri = null;
    try {
        addrUri = new URL(addr).toURI();
        addrPath = addrUri.getPath().toString();
        String query = addrUri.getQuery();
        if (query != null) {
            addrPath += "?" + query;
        }
    } catch (Exception ex) {
        LOG.error(ex, ex);
        return null;
    }

    HttpMethodBase method = null;
    if (httpVerb.equals("PUT")) {
        method = new PutMethodWithProgress(addr);
    } else if (httpVerb.equals("DELETE")) {
        method = new DeleteMethod(addr);
    } else {
        method = new GetMethod(addr);
    }

    method.setRequestHeader("Date", date);
    //method.setRequestHeader("Expect", "100-continue");

    method.setRequestHeader(EUCALYPTUS_OPERATION, eucaOperation);
    if (eucaHeader != null) {
        method.setRequestHeader(EUCALYPTUS_HEADER, eucaHeader);
    }

    if (signRequest) {
        signEucaInternal(method);
    }

    return method;
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java

private void setRequestHeaders(Map<String, String> headers, HttpMethodBase method) {
    if (headers != null) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            method.setRequestHeader(header.getKey(), header.getValue());
        }// w  ww. j a v  a 2  s.c o m
    }
}

From source file:net.sf.j2ep.requesthandlers.MaxForwardRequestHandler.java

/**
 * Sets the headers and does some checking for if this request
 * is meant for the server or for the proxy. This check is done
 * by looking at the Max-Forwards header.
 * //  www. j a  va  2  s  .c o  m
 * @see net.sf.j2ep.model.RequestHandler#process(javax.servlet.http.HttpServletRequest, java.lang.String)
 */
public HttpMethod process(HttpServletRequest request, String url) throws IOException {
    HttpMethodBase method = null;

    if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
        method = new OptionsMethod(url);
    } else if (request.getMethod().equalsIgnoreCase("TRACE")) {
        method = new TraceMethod(url);
    } else {
        return null;
    }

    try {
        int max = request.getIntHeader("Max-Forwards");
        if (max == 0 || request.getRequestURI().equals("*")) {
            setAllHeaders(method, request);
            method.abort();
        } else if (max != -1) {
            setHeaders(method, request);
            method.setRequestHeader("Max-Forwards", "" + max--);
        } else {
            setHeaders(method, request);
        }
    } catch (NumberFormatException e) {
    }

    return method;
}

From source file:flex.messaging.services.http.proxy.RequestFilter.java

/**
 * Add any custom headers.//w  w  w .j av a 2s.  c o  m
 *
 * @param context the context
 */
protected void addCustomHeaders(ProxyContext context) {
    HttpMethodBase httpMethod = context.getHttpMethod();

    String contentType = context.getContentType();
    if (contentType != null) {
        httpMethod.setRequestHeader(ProxyConstants.HEADER_CONTENT_TYPE, contentType);
    }

    Map customHeaders = context.getHeaders();
    if (customHeaders != null) {
        for (Object entry : customHeaders.entrySet()) {

            String name = (String) ((Map.Entry) entry).getKey();
            Object value = ((Map.Entry) entry).getValue();
            if (value == null) {
                httpMethod.setRequestHeader(name, "");
            }
            // Single value for the name.
            else if (value instanceof String) {
                httpMethod.setRequestHeader(name, (String) value);
            }
            // Multiple values for the name.
            else if (value instanceof List) {
                List valueList = (List) value;
                for (Object currentValue : valueList) {
                    if (currentValue == null) {
                        httpMethod.addRequestHeader(name, "");
                    } else {
                        httpMethod.addRequestHeader(name, (String) currentValue);
                    }
                }
            } else if (value.getClass().isArray()) {
                Object[] valueArray = (Object[]) value;
                for (Object currentValue : valueArray) {
                    if (currentValue == null) {
                        httpMethod.addRequestHeader(name, "");
                    } else {
                        httpMethod.addRequestHeader(name, (String) currentValue);
                    }
                }
            }
        }
    }

    if (context.isSoapRequest()) {
        // add the appropriate headers
        context.getHttpMethod().setRequestHeader(ProxyConstants.HEADER_CONTENT_TYPE,
                MessageIOConstants.CONTENT_TYPE_XML);

        // get SOAPAction, and if it doesn't exist, create it
        String soapAction = null;

        Header header = context.getHttpMethod().getRequestHeader(MessageIOConstants.HEADER_SOAP_ACTION);
        if (header != null) {
            soapAction = header.getValue();
        }

        if (soapAction == null) {
            HttpServletRequest clientRequest = FlexContext.getHttpRequest();
            if (clientRequest != null) {
                soapAction = clientRequest.getHeader(MessageIOConstants.HEADER_SOAP_ACTION);
            }

            // SOAPAction has to be quoted per the SOAP 1.1 spec.
            if (soapAction != null && !soapAction.startsWith("\"") && !soapAction.endsWith("\"")) {
                soapAction = "\"" + soapAction + "\"";
            }

            // If soapAction happens to still be null at this point, we'll end up not sending
            // one, which should generate a fault on the server side which we'll happily convey
            // back to the client.

            context.getHttpMethod().setRequestHeader(MessageIOConstants.HEADER_SOAP_ACTION, soapAction);
        }
    }
}

From source file:com.sittinglittleduck.DirBuster.Worker.java

private int makeRequest(HttpMethodBase httpMethod) throws HttpException, IOException, InterruptedException {
    if (Config.debug) {
        System.out.println("DEBUG Worker[" + threadId + "]: " + httpMethod.getName() + " : " + url.toString());
    }//from   w  w w.  j a v  a  2 s.co m

    // set the custom HTTP headers
    Vector HTTPheaders = manager.getHTTPHeaders();
    for (int a = 0; a < HTTPheaders.size(); a++) {
        HTTPHeader httpHeader = (HTTPHeader) HTTPheaders.elementAt(a);
        /*
         * Host header has to be set in a different way!
         */
        if (httpHeader.getHeader().startsWith("Host")) {
            httpMethod.getParams().setVirtualHost(httpHeader.getValue());
        } else {
            httpMethod.setRequestHeader(httpHeader.getHeader(), httpHeader.getValue());
        }
    }
    httpMethod.setFollowRedirects(Config.followRedirects);

    /*
     * this code is used to limit the number of request/sec
     */
    if (manager.isLimitRequests()) {
        while (manager.getTotalDone()
                / ((System.currentTimeMillis() - manager.getTimestarted()) / 1000.0) > manager
                        .getLimitRequestsTo()) {
            Thread.sleep(100);
        }
    }
    /*
     * Send the request
     */
    int code = httpclient.executeMethod(httpMethod);

    if (Config.debug) {
        System.out.println("DEBUG Worker[" + threadId + "]: " + code + " " + url.toString());
    }
    return code;
}

From source file:edu.uci.ics.pregelix.example.util.TestExecutor.java

public InputStream executeQuery(String str, OutputFormat fmt, String url,
        List<CompilationUnit.Parameter> params) throws Exception {
    HttpMethodBase method = null;
    if (str.length() + url.length() < MAX_URL_LENGTH) {
        //Use GET for small-ish queries
        method = new GetMethod(url);
        NameValuePair[] parameters = new NameValuePair[params.size() + 1];
        parameters[0] = new NameValuePair("query", str);
        int i = 1;
        for (CompilationUnit.Parameter param : params) {
            parameters[i++] = new NameValuePair(param.getName(), param.getValue());
        }/*from  w  w w.  jav  a2s.c  o m*/
        method.setQueryString(parameters);
    } else {
        //Use POST for bigger ones to avoid 413 FULL_HEAD
        // QQQ POST API doesn't allow encoding additional parameters
        method = new PostMethod(url);
        ((PostMethod) method).setRequestEntity(new StringRequestEntity(str));
    }

    //Set accepted output response type
    method.setRequestHeader("Accept", fmt.mimeType());
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    executeHttpMethod(method);
    return method.getResponseBodyAsStream();
}

From source file:com.snaker.DownloadManager.java

private Runnable createRunnable(final Downloader d) {
    final Task task = d.getTask();
    return new Runnable() {
        @Override/*from w ww . ja  v  a2  s. c om*/
        public void run() {
            logger.info("start download:" + d.getUrl());
            HttpClient client = clients.get(task.getId());
            DownloadHandler handler = d.getHandler();
            HttpMethodBase m = null;
            d.setStatus(Status.STARTED);
            d.setStartTime(System.currentTimeMillis());
            try {
                String url = d.getUrl();
                if (d.isGet()) {
                    GetMethod get = new GetMethod(url);
                    m = get;
                } else {
                    final String requestCharset = d.getRequestCharset();
                    PostMethod post = new PostMethod(url) {
                        public String getRequestCharSet() {
                            if (requestCharset != null)
                                return requestCharset;
                            else
                                return super.getRequestCharSet();
                        }

                        public boolean getFollowRedirects() {
                            return d.isFollowRedirects();
                        }
                    };
                    if (requestCharset != null) {
                        post.setRequestHeader("ContentType",
                                "application/x-www-form-urlencoded;charset=" + requestCharset);
                    }
                    DownloadParams parms = d.getParms();
                    if (parms != null)
                        post.setRequestBody(parms.toNVP());
                    m = post;
                }
                { // set the headers
                    m.setRequestHeader("User-Agent",
                            "Mozilla/5.0 (Windows NT 5.1; rv:8.0.1) Gecko/20100101 Firefox/8.0.1");
                    m.setRequestHeader("Accept",
                            "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                    m.setRequestHeader("Accept-Language", "en-us,zh-cn;q=0.5");
                    m.setRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                    m.setRequestHeader("Referer", url);
                }
                client.executeMethod(m);
                //check status
                int sc = m.getStatusCode();
                d.setStatusCode(sc);

                if (isBadStatusCode(sc)) {
                    logger.error("download failed,url:" + d.getUrl() + ",Status Code:" + sc);
                    d.setStatus(Status.FAILED);
                    d.setDescription(m.getStatusText());
                    return;
                } else if (sc == 404 || sc == 410) {
                    d.setStatus(Status.FINISHED);
                    d.setDescription("NOT FOUND");
                    return;
                }

                long size = m.getResponseContentLength();
                d.setFileSize(size);

                // get File Name
                if (d.getFileName() == null) {
                    Header h = m.getResponseHeader("Content-Disposition");
                    String fileName = null;
                    if (h != null) {
                        String f = h.getValue();
                        int tag = f.indexOf("filename=");
                        if (tag != -1 && tag != f.length() - 1)
                            fileName = f.substring(tag + 1);
                    }

                    if (fileName == null || fileName.length() == 0) {
                        int tag1 = url.lastIndexOf("/");
                        int tag2 = url.lastIndexOf("?");
                        if (tag1 != -1 && tag1 != url.length() - 1) {
                            if (tag2 > tag1) {
                                fileName = url.substring(tag1 + 1, tag2);
                            } else {
                                fileName = url.substring(tag1 + 1);
                            }
                        }
                    }
                    d.setFileName(fileName);
                }

                // set the all headers
                Header[] headers = m.getResponseHeaders();
                if (headers != null) {
                    for (Header header : headers) {
                        d.addResponseHeader(header.getName(), header.getValue());
                    }
                }
                d.setStatus(Status.RUNNING);
                // recv the body
                if (handler == null) {
                    byte[] content = m.getResponseBody();
                    int len = content.length;
                    d.setFileSize(len);
                    d.setReceived(len);
                    d.setResponseCharset(m.getResponseCharSet());
                    d.setResponseBody(content);
                } else {
                    InputStream is = m.getResponseBodyAsStream();
                    handler.start(d);
                    byte[] buffer = new byte[102400];
                    long count = 0;
                    while (true) {
                        int r = is.read(buffer);
                        if (r > 0) {
                            count += r;
                            d.setReceived(count);
                            handler.handle(buffer, r);
                        } else {
                            break;
                        }
                    }
                    is.close();
                }
                d.setStatus(Status.FINISHED);
            } catch (Exception e) {
                logger.error("download failed,url:" + d.getUrl(), e);
                d.setStatus(Status.FAILED);
                d.setDescription(e.getMessage());
            } finally {
                m.releaseConnection();
                if (handler != null) {
                    handler.stop();
                }
                downloadings.remove(d);
                d.setEndTime(System.currentTimeMillis());
                while (downloaded.size() >= maxDownloadedCount) {
                    downloaded.poll();
                }
                downloaded.offer(d);
                task.downloadFininshed(d);
            }
        }
    };
}

From source file:com.esri.gpt.framework.http.HttpClientRequest.java

/**
 * Create the HTTP method./*w w w .  j  a v a 2  s .c o m*/
 * <br/>A GetMethod will be created if the RequestEntity associated with
 * the ContentProvider is null. Otherwise, a PostMethod will be created.
 * @return the HTTP method
 */
private HttpMethodBase createMethod() throws IOException {
    HttpMethodBase method = null;
    MethodName name = this.getMethodName();

    // make the method
    if (name == null) {
        if (this.getContentProvider() == null) {
            this.setMethodName(MethodName.GET);
            method = new GetMethod(this.getUrl());
        } else {
            this.setMethodName(MethodName.POST);
            method = new PostMethod(this.getUrl());
        }
    } else if (name.equals(MethodName.DELETE)) {
        method = new DeleteMethod(this.getUrl());
    } else if (name.equals(MethodName.GET)) {
        method = new GetMethod(this.getUrl());
    } else if (name.equals(MethodName.POST)) {
        method = new PostMethod(this.getUrl());
    } else if (name.equals(MethodName.PUT)) {
        method = new PutMethod(this.getUrl());
    }

    // write the request body if necessary
    if (this.getContentProvider() != null) {
        if (method instanceof EntityEnclosingMethod) {
            EntityEnclosingMethod eMethod = (EntityEnclosingMethod) method;
            RequestEntity eAdapter = getContentProvider() instanceof MultiPartContentProvider
                    ? new MultiPartProviderAdapter(this, eMethod,
                            (MultiPartContentProvider) getContentProvider())
                    : new ApacheEntityAdapter(this, this.getContentProvider());
            eMethod.setRequestEntity(eAdapter);
            if (eAdapter.getContentType() != null) {
                eMethod.setRequestHeader("Content-type", eAdapter.getContentType());
            }
        } else {
            // TODO: possibly will need an exception here in the future
        }
    }

    // set headers, add the retry method
    for (Map.Entry<String, String> hdr : this.requestHeaders.entrySet()) {
        method.addRequestHeader(hdr.getKey(), hdr.getValue());
    }

    // declare possible gzip handling
    method.setRequestHeader("Accept-Encoding", "gzip");

    this.addRetryHandler(method);
    return method;
}