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:org.collectionspace.chain.csp.persistence.services.connection.ServicesConnection.java

private void doRequest(Returned out, RequestMethod method_type, String uri, RequestDataSource src,
        CSPRequestCredentials creds, CSPRequestCache cache) throws ConnectionException {
    InputStream body_data = null;
    if (src != null) {
        body_data = src.getStream();//from  w  w w .  jav  a2  s.  c o  m
    }
    try {
        HttpMethod method = createMethod(method_type, uri, body_data);
        if (body_data != null) {
            method.setRequestHeader("Content-Type", src.getMIMEType());
            // XXX Not sure if or when this ever actually writes to stderr?
            body_data = new TeeInputStream(body_data, System.err);
        }
        try {
            HttpClient client = makeClient(creds, cache);

            String requestContext = null;
            if (perflog.isDebugEnabled()) {
                // TODO add more context, e.g. session id?
                requestContext = "HttpClient@" + Integer.toHexString(client.hashCode());
                requestContext += "/CSPRequestCache@" + Integer.toHexString(cache.hashCode()) + ",";
                //String queryString = method.getQueryString();
                perflog.debug(System.currentTimeMillis() + ",\"" + Thread.currentThread().getName()
                        + "\",app,svc," + requestContext + method.getName() + " " + method.getURI()
                //+ (queryString!=null ? queryString : "")
                );
            }

            int response = client.executeMethod(method);

            if (perflog.isDebugEnabled()) {
                perflog.debug(System.currentTimeMillis() + ",\"" + Thread.currentThread().getName()
                        + "\",svc,app," + requestContext + "HttpClient.executeMethod done");
            }

            out.setResponse(method, response);
        } catch (ConnectionException e) {
            throw new ConnectionException(e.getMessage(), e.status, base_url + "/" + uri, e);
        } catch (Exception e) {
            throw new ConnectionException(e.getMessage(), 0, base_url + "/" + uri, e);
        } finally {
            method.releaseConnection();

            if (log.isWarnEnabled()) {
                if (manager.getConnectionsInPool() >= MAX_SERVICES_CONNECTIONS) {
                    log.warn("reached max services connection limit of " + MAX_SERVICES_CONNECTIONS);

                    // Delete closed connections from the pool, so that the warning will cease
                    // once a connection becomes available.
                    manager.deleteClosedConnections();
                }
            }
        }
    } finally {
        closeStream(body_data);
    }
}

From source file:org.deegree.framework.util.HttpUtils.java

private static void setHTTPCredentials(HttpMethod m, String user, String password) {
    if (user != null) {
        if (password == null) {
            password = "";
        }/*from   ww  w .j a  va2 s.  c  o  m*/
        String s = new String(Base64.encodeBase64((user + ":" + password).getBytes()));
        m.setRequestHeader("authorization", "Basic " + s);
    }
}

From source file:org.eclipsetrader.yahoojapanfx.internal.core.Util.java

private static void setCommonRequestHeaders(HttpMethod method) {
    method.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:24.0) Gecko/20100101 Firefox/24.0");
    method.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    method.setRequestHeader("Accept-Language", "ja,en-us;q=0.7,en;q=0.3");
    method.setRequestHeader("Accept-Encoding", "gzip, deflate");
}

From source file:org.fao.geonet.services.publisher.GeoServerRest.java

/**
 * //from   ww w  . j a  v a 2 s . c o  m
 * @param method
 *            e.g. 'POST', 'GET', 'PUT' or 'DELETE'
 * @param urlParams
 *            REST API parameter
 * @param postData
 *            XML data
 * @param file
 *            File to upload
 * @param contentType
 *            type of content in case of post data or file updload.
 * @param saveResponse
 * @return
 * @throws IOException
 */
public int sendREST(String method, String urlParams, String postData, File file, String contentType,
        Boolean saveResponse) throws IOException {

    response = "";
    final HttpClient c = httpClientFactory.newHttpClient();
    String url = this.restUrl + urlParams;
    if (Log.isDebugEnabled(LOGGER_NAME)) {
        Log.debug(LOGGER_NAME, "url:" + url);
        Log.debug(LOGGER_NAME, "method:" + method);
        Log.debug(LOGGER_NAME, "postData:" + postData);
    }

    HttpMethod m;
    if (method.equals(METHOD_PUT)) {
        m = new PutMethod(url);
        if (file != null) {
            ((PutMethod) m).setRequestEntity(new InputStreamRequestEntity(new FileInputStream(file)));
        }
        if (postData != null) {
            ((PutMethod) m).setRequestEntity(new StringRequestEntity(postData, contentType, "UTF-8"));
        }
    } else if (method.equals(METHOD_DELETE)) {
        m = new DeleteMethod(url);
    } else if (method.equals(METHOD_POST)) {
        m = new PostMethod(url);
        if (postData != null) {
            ((PostMethod) m).setRequestEntity(new StringRequestEntity(postData, contentType, "UTF-8"));
        }

    } else {
        m = new GetMethod(url);
    }

    if (contentType != null && !"".equals(contentType)) {
        m.setRequestHeader("Content-type", contentType);
    }

    m.setDoAuthentication(true);

    status = c.executeMethod(m);
    if (Log.isDebugEnabled(LOGGER_NAME))
        Log.debug(LOGGER_NAME, "status:" + status);
    if (saveResponse)
        this.response = m.getResponseBodyAsString();

    return status;
}

From source file:org.geoserver.wps.Execute.java

/**
 * Executes//ww w. j  a va 2 s  . co  m
 * 
 * @param ref
 * @return
 */
Object executeRemoteRequest(InputReferenceType ref, ComplexPPIO ppio, String inputId) throws Exception {
    URL destination = new URL(ref.getHref());

    HttpMethod method = null;
    GetMethod refMethod = null;
    InputStream input = null;
    InputStream refInput = null;

    // execute the request
    try {
        if ("http".equalsIgnoreCase(destination.getProtocol())) {
            // setup the client
            HttpClient client = new HttpClient();
            // setting timeouts (30 seconds, TODO: make this configurable)
            HttpConnectionManagerParams params = new HttpConnectionManagerParams();
            params.setSoTimeout(connectionTimeout);
            params.setConnectionTimeout(connectionTimeout);
            // TODO: make the http client a well behaved http client, no more than x connections
            // per server (x admin configurable maybe), persistent connections and so on
            HttpConnectionManager manager = new SimpleHttpConnectionManager();
            manager.setParams(params);
            client.setHttpConnectionManager(manager);

            // prepare either a GET or a POST request
            if (ref.getMethod() == null || ref.getMethod() == MethodType.GET_LITERAL) {
                GetMethod get = new GetMethod(ref.getHref());
                get.setFollowRedirects(true);
                method = get;
            } else {
                String encoding = ref.getEncoding();
                if (encoding == null) {
                    encoding = "UTF-8";
                }

                PostMethod post = new PostMethod(ref.getHref());
                Object body = ref.getBody();
                if (body == null) {
                    if (ref.getBodyReference() != null) {
                        URL refDestination = new URL(ref.getBodyReference().getHref());
                        if ("http".equalsIgnoreCase(refDestination.getProtocol())) {
                            // open with commons http client
                            refMethod = new GetMethod(ref.getBodyReference().getHref());
                            refMethod.setFollowRedirects(true);
                            client.executeMethod(refMethod);
                            refInput = refMethod.getResponseBodyAsStream();
                        } else {
                            // open with the built-in url management
                            URLConnection conn = refDestination.openConnection();
                            conn.setConnectTimeout(connectionTimeout);
                            conn.setReadTimeout(connectionTimeout);
                            refInput = conn.getInputStream();
                        }
                        post.setRequestEntity(new InputStreamRequestEntity(refInput, ppio.getMimeType()));
                    } else {
                        throw new WPSException("A POST request should contain a non empty body");
                    }
                } else if (body instanceof String) {
                    post.setRequestEntity(new StringRequestEntity((String) body, ppio.getMimeType(), encoding));
                } else {
                    throw new WPSException("The request body should be contained in a CDATA section, "
                            + "otherwise it will get parsed as XML instead of being preserved as is");

                }
                method = post;
            }
            // add eventual extra headers
            if (ref.getHeader() != null) {
                for (Iterator it = ref.getHeader().iterator(); it.hasNext();) {
                    HeaderType header = (HeaderType) it.next();
                    method.setRequestHeader(header.getKey(), header.getValue());
                }
            }
            int code = client.executeMethod(method);

            if (code == 200) {
                input = method.getResponseBodyAsStream();
            } else {
                throw new WPSException("Error getting remote resources from " + ref.getHref() + ", http error "
                        + code + ": " + method.getStatusText());
            }
        } else {
            // use the normal url connection methods then...
            URLConnection conn = destination.openConnection();
            conn.setConnectTimeout(connectionTimeout);
            conn.setReadTimeout(connectionTimeout);
            input = conn.getInputStream();
        }

        // actually parse teh data
        if (input != null) {
            return ppio.decode(input);
        } else {
            throw new WPSException("Could not find a mean to read input " + inputId);
        }
    } finally {
        // make sure to close the connection and streams no matter what
        if (input != null) {
            input.close();
        }
        if (method != null) {
            method.releaseConnection();
        }
        if (refMethod != null) {
            refMethod.releaseConnection();
        }
    }
}

From source file:org.geoserver.wps.executor.RemoteRequestInputProvider.java

@Override
protected Object getValueInternal(ProgressListener listener) throws Exception {
    InputReferenceType ref = input.getReference();
    URL destination = new URL(ref.getHref());

    HttpMethod method = null;
    GetMethod refMethod = null;/*from w  ww .j a  v a  2s  . c o m*/
    InputStream input = null;
    InputStream refInput = null;

    // execute the request
    listener.started();
    try {
        if ("file".equalsIgnoreCase(destination.getProtocol())) {
            File file = DataUtilities.urlToFile(destination);
            if (maxSize > 0 && maxSize < file.length()) {
                throw new WPSException("Input " + getInputId() + " size " + file.length()
                        + " exceeds maximum allowed size of " + maxSize, "NoApplicableCode", getInputId());
            }

            input = new FileInputStream(file);
        } else if ("http".equalsIgnoreCase(destination.getProtocol())) {
            // setup the client
            HttpClient client = new HttpClient();
            // setting timeouts (30 seconds, TODO: make this configurable)
            HttpConnectionManagerParams params = new HttpConnectionManagerParams();
            params.setSoTimeout(timeout);
            params.setConnectionTimeout(timeout);
            // TODO: make the http client a well behaved http client, no more than x connections
            // per server (x admin configurable maybe), persistent connections and so on
            HttpConnectionManager manager = new SimpleHttpConnectionManager();
            manager.setParams(params);
            client.setHttpConnectionManager(manager);

            // prepare either a GET or a POST request
            if (ref.getMethod() == null || ref.getMethod() == MethodType.GET_LITERAL) {
                GetMethod get = new GetMethod(ref.getHref());
                get.setFollowRedirects(true);
                method = get;
            } else {
                String encoding = ref.getEncoding();
                if (encoding == null) {
                    encoding = "UTF-8";
                }

                PostMethod post = new PostMethod(ref.getHref());
                Object body = ref.getBody();
                if (body == null) {
                    if (ref.getBodyReference() != null) {
                        URL refDestination = new URL(ref.getBodyReference().getHref());
                        if ("http".equalsIgnoreCase(refDestination.getProtocol())) {
                            // open with commons http client
                            refMethod = new GetMethod(ref.getBodyReference().getHref());
                            refMethod.setFollowRedirects(true);
                            client.executeMethod(refMethod);
                            refInput = refMethod.getResponseBodyAsStream();
                        } else {
                            // open with the built-in url management
                            URLConnection conn = refDestination.openConnection();
                            conn.setConnectTimeout(timeout);
                            conn.setReadTimeout(timeout);
                            refInput = conn.getInputStream();
                        }
                        post.setRequestEntity(
                                new InputStreamRequestEntity(refInput, complexPPIO.getMimeType()));
                    } else {
                        throw new WPSException("A POST request should contain a non empty body");
                    }
                } else if (body instanceof String) {
                    post.setRequestEntity(
                            new StringRequestEntity((String) body, complexPPIO.getMimeType(), encoding));
                } else {
                    throw new WPSException("The request body should be contained in a CDATA section, "
                            + "otherwise it will get parsed as XML instead of being preserved as is");

                }
                method = post;
            }
            // add eventual extra headers
            if (ref.getHeader() != null) {
                for (Iterator it = ref.getHeader().iterator(); it.hasNext();) {
                    HeaderType header = (HeaderType) it.next();
                    method.setRequestHeader(header.getKey(), header.getValue());
                }
            }
            int code = client.executeMethod(method);

            if (code == 200) {
                try {
                    Header length = method.getResponseHeader("Content-Lenght");
                    if (maxSize > 0 && length != null && Long.parseLong(length.getValue()) > maxSize) {
                        throw new WPSException(
                                "Input " + getInputId() + " size " + length.getValue()
                                        + " exceeds maximum allowed size of " + maxSize
                                        + " according to HTTP Content-Lenght response header",
                                "NoApplicableCode", getInputId());
                    }
                } catch (NumberFormatException e) {
                    LOGGER.log(Level.FINE, "Failed to parse content lenght to check input limits respect, "
                            + "moving on and checking data as it comes in", e);
                }
                input = method.getResponseBodyAsStream();
                if (maxSize > 0) {
                    input = new MaxSizeInputStream(input, getInputId(), maxSize);
                }
            } else {
                throw new WPSException("Error getting remote resources from " + ref.getHref() + ", http error "
                        + code + ": " + method.getStatusText());
            }
        } else {
            // use the normal url connection methods then...
            URLConnection conn = destination.openConnection();
            conn.setConnectTimeout(timeout);
            conn.setReadTimeout(timeout);
            input = conn.getInputStream();

            if (maxSize > 0) {
                input = new MaxSizeInputStream(input, getInputId(), maxSize);
            }
        }

        // actually parse the data
        if (input != null) {
            CancellingInputStream is = new CancellingInputStream(input, listener);
            return complexPPIO.decode(is);
        } else {
            throw new WPSException("Could not find a mean to read input " + inputId);
        }
    } finally {
        listener.progress(100);
        listener.complete();
        // make sure to close the connection and streams no matter what
        if (refInput != null) {
            refInput.close();
        }
        if (input != null) {
            input.close();
        }
        if (method != null) {
            method.releaseConnection();
        }
        if (refMethod != null) {
            refMethod.releaseConnection();
        }
    }
}

From source file:org.geoserver.wps.executor.SimpleInputProvider.java

/**
 * Executes//w  w w.  jav  a  2  s . c  o  m
 * 
 * @param ref
 * @return
 */
Object executeRemoteRequest(InputReferenceType ref, ComplexPPIO ppio, String inputId) throws Exception {
    URL destination = new URL(ref.getHref());

    HttpMethod method = null;
    GetMethod refMethod = null;
    InputStream input = null;
    InputStream refInput = null;

    // execute the request
    try {
        if ("http".equalsIgnoreCase(destination.getProtocol())) {
            // setup the client
            HttpClient client = new HttpClient();
            // setting timeouts (30 seconds, TODO: make this configurable)
            HttpConnectionManagerParams params = new HttpConnectionManagerParams();
            params.setSoTimeout(executor.getConnectionTimeout());
            params.setConnectionTimeout(executor.getConnectionTimeout());
            // TODO: make the http client a well behaved http client, no more than x connections
            // per server (x admin configurable maybe), persistent connections and so on
            HttpConnectionManager manager = new SimpleHttpConnectionManager();
            manager.setParams(params);
            client.setHttpConnectionManager(manager);

            // prepare either a GET or a POST request
            if (ref.getMethod() == null || ref.getMethod() == MethodType.GET_LITERAL) {
                GetMethod get = new GetMethod(ref.getHref());
                get.setFollowRedirects(true);
                method = get;
            } else {
                String encoding = ref.getEncoding();
                if (encoding == null) {
                    encoding = "UTF-8";
                }

                PostMethod post = new PostMethod(ref.getHref());
                Object body = ref.getBody();
                if (body == null) {
                    if (ref.getBodyReference() != null) {
                        URL refDestination = new URL(ref.getBodyReference().getHref());
                        if ("http".equalsIgnoreCase(refDestination.getProtocol())) {
                            // open with commons http client
                            refMethod = new GetMethod(ref.getBodyReference().getHref());
                            refMethod.setFollowRedirects(true);
                            client.executeMethod(refMethod);
                            refInput = refMethod.getResponseBodyAsStream();
                        } else {
                            // open with the built-in url management
                            URLConnection conn = refDestination.openConnection();
                            conn.setConnectTimeout(executor.getConnectionTimeout());
                            conn.setReadTimeout(executor.getConnectionTimeout());
                            refInput = conn.getInputStream();
                        }
                        post.setRequestEntity(new InputStreamRequestEntity(refInput, ppio.getMimeType()));
                    } else {
                        throw new WPSException("A POST request should contain a non empty body");
                    }
                } else if (body instanceof String) {
                    post.setRequestEntity(new StringRequestEntity((String) body, ppio.getMimeType(), encoding));
                } else {
                    throw new WPSException("The request body should be contained in a CDATA section, "
                            + "otherwise it will get parsed as XML instead of being preserved as is");

                }
                method = post;
            }
            // add eventual extra headers
            if (ref.getHeader() != null) {
                for (Iterator it = ref.getHeader().iterator(); it.hasNext();) {
                    HeaderType header = (HeaderType) it.next();
                    method.setRequestHeader(header.getKey(), header.getValue());
                }
            }
            int code = client.executeMethod(method);

            if (code == 200) {
                input = method.getResponseBodyAsStream();
            } else {
                throw new WPSException("Error getting remote resources from " + ref.getHref() + ", http error "
                        + code + ": " + method.getStatusText());
            }
        } else {
            // use the normal url connection methods then...
            URLConnection conn = destination.openConnection();
            conn.setConnectTimeout(executor.getConnectionTimeout());
            conn.setReadTimeout(executor.getConnectionTimeout());
            input = conn.getInputStream();
        }

        // actually parse teh data
        if (input != null) {
            return ppio.decode(input);
        } else {
            throw new WPSException("Could not find a mean to read input " + inputId);
        }
    } finally {
        // make sure to close the connection and streams no matter what
        if (input != null) {
            input.close();
        }
        if (method != null) {
            method.releaseConnection();
        }
        if (refMethod != null) {
            refMethod.releaseConnection();
        }
    }
}

From source file:org.gradle.api.internal.artifacts.repositories.CommonsHttpClientBackedRepository.java

private void configureMethod(HttpMethod method) {
    method.setRequestHeader("User-Agent", "Gradle/" + GradleVersion.current().getVersion());
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new HttpMethodRetryHandler() {
        public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) {
            return false;
        }//from   www.  j  ava  2 s . com
    });
}

From source file:org.gradle.api.internal.artifacts.repositories.transport.http.HttpResourceCollection.java

private void configureMethod(HttpMethod method) {
    method.setRequestHeader("User-Agent", "Gradle/" + GradleVersion.current().getVersion());
    method.setRequestHeader("Accept-Encoding", "identity");
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new HttpMethodRetryHandler() {
        public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) {
            return false;
        }/*from   ww w .j  ava 2  s . co m*/
    });
}

From source file:org.infoscoop.request.ProxyRequestTest.java

public static void main(String args[]) throws HttpException, IOException {
    //testActiveMailFilter();
    //testCalendarFilter();
    //testNekoFilter();
    //testMakeMenuFilter();
    //testRssFilter();
    //testNoOperationFilter();
    //testURLReplaceFilter();
    //testMaximizeGadgetFilter();
    //testSearchResultFilter();

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod("http://loclahost/ntlmtest/inicio.xml");
    method.setRequestHeader("Accept",
            "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*");
    method.setRequestHeader("Accept-Language", "ja,en;q=0.5");
    method.setRequestHeader("Accept-Encoding", "gzip, deflate");
    method.setRequestHeader("If-Modified-Since", "Wed, 14 May 2008 07:15:21 GMT");
    method.setRequestHeader("If-None-Match", "\"3d6c2-23f3-8b33cdb5\"");
    method.setRequestHeader("User-Agent",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)");
    method.setRequestHeader("Host", "localhost");
    method.setRequestHeader("Connection", "Keep-Alive");
    method.setRequestHeader("Authorization",
            "NTLM TlRMTVNTUAADAAAAAAAAAEgAAAAAAAAASAAAAAAAAABIAAAAAAAAAEgAAAAAAAAASAAAAAAAAABIAAAABcKIogUBKAoAAAAP");
    method.setRequestHeader("Cookie", "Apache=58.80.230.67.214291213856606176");
    client.executeMethod(method);//from  w w w  .ja  v  a  2  s  .c  om
    method.getResponseBody();
}