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.pengyou.client.lib.DavResource.java

/**
 * Generate and add the If header to the specified HTTP method.
 *///w ww .  ja  v a  2 s  . c  om
protected void generateIfHeader(HttpMethod method) {

    if (client == null)
        return;
    if (method == null)
        return;

    WebdavState state = (WebdavState) this.client.getState();
    String[] lockTokens = state.getAllLocks(method.getPath());

    if (lockTokens.length == 0)
        return;

    StringBuffer ifHeaderValue = new StringBuffer();

    for (int i = 0; i < lockTokens.length; i++) {
        ifHeaderValue.append("(<").append(lockTokens[i]).append(">) ");
    }

    method.setRequestHeader("If", ifHeaderValue.toString());

}

From source file:org.sakaiproject.nakamura.grouper.changelog.util.NakamuraHttpUtils.java

/**
 * Prepare an HTTP request to Sakai OAE and parse the response (if JSON).
 * @param client an {@link HttpClient} to execute the request.
 * @param method an HTTP method to send//from   w  w  w.  j  a  va  2  s.  co m
 * @return a JSONObject of the response if the request returns JSON
 * @throws GroupModificationException if there was an error updating the group information.
 */
public static JSONObject http(HttpClient client, HttpMethod method) throws GroupModificationException {

    method.setRequestHeader("User-Agent", HTTP_USER_AGENT);
    method.setRequestHeader("Referer", HTTP_REFERER);

    String errorMessage = null;
    String responseString = null;
    JSONObject responseJSON = null;

    boolean isJSONRequest = !method.getPath().toString().endsWith(".html");

    if (log.isDebugEnabled() && method instanceof PostMethod) {
        log.debug(method.getName() + " " + method.getPath() + " params:");
        for (NameValuePair nvp : ((PostMethod) method).getParameters()) {
            log.debug(nvp.getName() + " = " + nvp.getValue());
        }
    }

    int responseCode = -1;
    try {
        responseCode = client.executeMethod(method);
        responseString = StringUtils.trimToNull(IOUtils.toString(method.getResponseBodyAsStream()));

        if (isJSONRequest) {
            responseJSON = parseJSONResponse(responseString);
        }

        if (log.isDebugEnabled()) {
            log.debug(responseCode + " " + method.getName() + " " + method.getPath());
        }
        if (log.isTraceEnabled()) {
            log.trace("reponse: " + responseString);
        }

        switch (responseCode) {

        case HttpStatus.SC_OK: // 200
        case HttpStatus.SC_CREATED: // 201
            break;
        case HttpStatus.SC_BAD_REQUEST: // 400
        case HttpStatus.SC_UNAUTHORIZED: // 401
        case HttpStatus.SC_NOT_FOUND: // 404
        case HttpStatus.SC_INTERNAL_SERVER_ERROR: // 500
            if (isJSONRequest && responseJSON != null) {
                errorMessage = responseJSON.getString("status.message");
            }
            if (errorMessage == null) {
                errorMessage = "Empty " + responseCode + " error. Check the logs on the Sakai OAE server.";
            }
            break;
        default:
            errorMessage = "Unknown HTTP response " + responseCode;
            break;
        }
    } catch (Exception e) {
        errorMessage = "An exception occurred communicatingSakai OAE. " + e.toString();
    } finally {
        method.releaseConnection();
    }

    if (errorMessage != null) {
        log.error(errorMessage);
        errorToException(responseCode, errorMessage);
    }
    return responseJSON;
}

From source file:org.soasecurity.wso2.mutual.auth.oauth2.client.MutualSSLOAuthClient.java

public static void main(String[] args) throws Exception {

    File file = new File((new File(".")).getCanonicalPath() + File.separator + "src" + File.separator + "main"
            + File.separator + "resources" + File.separator + "keystore" + File.separator + keyStoreName);

    if (!file.exists()) {
        throw new Exception("Key Store file can not be found in " + file.getCanonicalPath());
    }//from  w w w  .ja va  2  s . c o m

    //Set trust store, you need to import server's certificate of CA certificate chain in to this
    //key store
    System.setProperty("javax.net.ssl.trustStore", file.getCanonicalPath());
    System.setProperty("javax.net.ssl.trustStorePassword", keyStorePassword);

    //Set key store, this must contain the user private key
    //here we have use both trust store and key store as the same key store
    //But you can use a separate key store for key store an trust store.
    System.setProperty("javax.net.ssl.keyStore", file.getCanonicalPath());
    System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword);

    HttpClient client = new HttpClient();

    HttpMethod method = new PostMethod(endPoint);

    // Base64 encoded client id & secret
    method.setRequestHeader("Authorization",
            "Basic T09pN2dpUjUwdDZtUmU1ZkpmWUhVelhVa1QwYTpOOUI2dDZxQ0E2RFp2eTJPQkFIWDhjVlI1eUlh");
    method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    NameValuePair pair1 = new NameValuePair();
    pair1.setName("grant_type");
    pair1.setValue("x509");

    NameValuePair pair2 = new NameValuePair();
    pair2.setName("username");
    pair2.setValue("asela");

    NameValuePair pair3 = new NameValuePair();
    pair3.setName("password");
    pair3.setValue("asela");

    method.setQueryString(new NameValuePair[] { pair1, pair2, pair3 });

    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {

        System.out.println("Failed: " + method.getStatusLine());

    } else {

        byte[] responseBody = method.getResponseBody();

        System.out.println(new String(responseBody));
    }
}

From source file:org.switchyard.component.test.mixins.http.HTTPMixIn.java

/**
 * Execute the supplied HTTP Method./*from w  ww . ja va  2 s.c om*/
 * <p/>
 * Does not release the {@link org.apache.commons.httpclient.HttpMethod#releaseConnection() HttpMethod connection}.
 *
 * @param method The HTTP Method.
 * @return The HTTP Response.
 */
public String execute(HttpMethod method) {
    if (_httpClient == null) {
        Assert.fail(
                "HTTPMixIn not initialized.  You must call the initialize() method before using this MixIn");
    }

    for (String key : _requestHeaders.keySet()) {
        method.setRequestHeader(key, _requestHeaders.get(key));
    }

    if (_dumpMessages) {
        for (Header header : method.getRequestHeaders()) {
            _logger.info("Request header:[" + header.getName() + "=" + header.getValue() + "]");
        }
    }

    String response = null;
    try {
        _httpClient.executeMethod(method);
        response = method.getResponseBodyAsString();
    } catch (Exception e) {
        try {
            Assert.fail("Exception invoking HTTP endpoint '" + method.getURI() + "': " + e.getMessage());
        } catch (URIException e1) {
            _logger.error("Unexpected error", e1);
            return null;
        }
    }

    if (_dumpMessages) {
        for (Header header : method.getResponseHeaders()) {
            _logger.info("Received response header:[" + header.getName() + "=" + header.getValue() + "]");
        }
        _logger.info("Received response body:[" + response + "]");
    }

    for (String key : _expectedHeaders.keySet()) {
        Header actual = method.getResponseHeader(key);
        Assert.assertNotNull("Checking response header:[" + key + "]", actual);
        Assert.assertEquals("Checking response header:[" + key + "]", _expectedHeaders.get(key),
                actual.getValue());
    }

    return response;
}

From source file:org.tuleap.mylyn.task.core.internal.client.rest.TuleapRestConnector.java

/**
 * {@inheritDoc}/*  w  ww  .j  a  v  a2s .c  o m*/
 *
 * @see org.tuleap.mylyn.task.core.internal.client.rest.IRestConnector#sendRequest(org.apache.commons.httpclient.HttpMethod)
 */
@Override
public ServerResponse sendRequest(HttpMethod method) {
    // debug mode
    boolean debug = false;
    IEclipsePreferences node = InstanceScope.INSTANCE.getNode(ITuleapConstants.TULEAP_PREFERENCE_NODE);
    if (node != null) {
        debug = node.getBoolean(ITuleapConstants.TULEAP_PREFERENCE_DEBUG_MODE, false);
    }

    if (hostConfiguration == null) {
        hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, null);
    }

    method.setRequestHeader("Accept", "application/json"); //$NON-NLS-1$ //$NON-NLS-2$
    method.setRequestHeader("Accept-Charset", "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
    method.setRequestHeader("Content-Type", "application/json"); //$NON-NLS-1$ //$NON-NLS-2$

    WebUtil.configureHttpClient(httpClient, getUserAgent());

    Header[] responseHeaders = null;
    String responseBody = null;
    ServerResponse serverResponse = null;
    try {
        int code = WebUtil.execute(httpClient, hostConfiguration, method, null);
        responseBody = method.getResponseBodyAsString();
        responseHeaders = method.getResponseHeaders();
        if (debug) {
            debugRestCall(method, responseBody);
        }
        Map<String, String> rHeaders = new LinkedHashMap<String, String>();
        for (Header h : responseHeaders) {
            rHeaders.put(h.getName(), h.getValue());
        }
        serverResponse = new ServerResponse(code, responseBody, rHeaders);
    } catch (IOException e) {
        logger.log(new Status(IStatus.ERROR, TuleapCoreActivator.PLUGIN_ID, TuleapCoreMessages
                .getString(TuleapCoreKeys.ioError, method.getName() + ' ' + method.getPath(), e.getMessage())));
        serverResponse = new ServerResponse(IO_ERROR_STATUS_CODE, "", Collections //$NON-NLS-1$
                .<String, String>emptyMap());
    } finally {
        method.releaseConnection();
    }

    return serverResponse;
}

From source file:org.wso2.carbon.mashup.javascript.hostobjects.pooledhttpclient.PooledHttpClientHostObject.java

/**
 * Used by jsFunction_executeMethod()./*from   ww w .j a  v  a2 s .  c  o  m*/
 * 
 * @param httpMethod
 * @param headers
 */
private static void setHeaders(HttpMethod httpMethod, NativeArray headers) {
    // headers array is parsed and headers are set
    String hName;
    String hValue;
    NativeObject header;
    for (int i = 0; i < headers.getLength(); i++) {
        header = (NativeObject) headers.get(i, headers);
        if (ScriptableObject.getProperty(header, "name") instanceof String
                && ScriptableObject.getProperty(header, "value") instanceof String) {

            hName = (String) ScriptableObject.getProperty(header, "name");
            hValue = (String) ScriptableObject.getProperty(header, "value");

            httpMethod.setRequestHeader(hName, hValue);
        } else {
            throw new RuntimeException("Name-Value pairs of headers should be Strings");
        }
    }
}

From source file:org.wso2.carbon.remotetasks.core.RemoteTask.java

@Override
public void execute() {
    boolean systemTask = this.isSystemTask();
    if (!systemTask) {
        this.notifyTaskManager();
    }/*from   w  w  w . java  2 s .c  om*/
    String targetURI = this.getProperties().get(RemoteTasksConstants.REMOTE_TASK_URI);
    if (targetURI == null || targetURI.length() == 0) {
        return;
    }
    HttpClient client = new HttpClient();
    client.getParams().setSoTimeout(DEFAULT_CONNECTION_TIMEOUT);
    HttpMethod method = new GetMethod(targetURI);
    if (systemTask) {
        method.setRequestHeader(RemoteTasksConstants.REMOTE_SYSTEM_TASK_HEADER_ID,
                this.getProperties().get(RemoteTasksConstants.REMOTE_SYSTEM_TASK_ID));
    }
    try {
        if (log.isDebugEnabled()) {
            log.debug("Executing remote task to URI: " + targetURI);
        }
        client.executeMethod(method);
        if (log.isDebugEnabled()) {
            StringBuilder builder = new StringBuilder();
            builder.append("Response Headers:-\n");
            for (Header header : method.getResponseHeaders()) {
                builder.append("\t" + header.getName() + ": " + header.getValue() + "\n");
            }
            log.debug(builder.toString());
        }
        String body = method.getResponseBodyAsString();
        if (log.isDebugEnabled()) {
            log.debug("Response Body:-\n\t" + body);
        }
        method.releaseConnection();
    } catch (Exception e) {
        log.error("Error executing remote task: " + e.getMessage(), e);
    }
}

From source file:smilehouse.opensyncro.defaultcomponents.http.HTTPUtils.java

/**
 * Makes a HTTP request to the specified url with a set of parameters,
  * request method, user name and password
 * //from  ww w .  j  a  v a2  s .c o  m
 * @param url the <code>URL</code> to make a request to 
 * @param method either "GET", "POST", "PUT" or "SOAP"
 * @param parameters two dimensional string array containing parameters to send in the request
 * @param user user name to submit in the request 
 * @param password password to submit in the request
 * @param charsetName charset name used for message content encoding
  * @param responseCharsetName charset name used to decode HTTP responses,
  *                            or null to use default ("ISO-8859-1")
  * @param contentType Content-Type header value (without charset information)
  *                    for POST (and SOAP) type requests. If null, defaults to
  *                    "text/xml".
 * @return a string array containing the body of the response, the headers of
  *         the response and possible error message
 * @throws Exception 
 */
public static HTTPResponse makeRequest(URL url, String method, String[][] parameters, String user,
        String password, String charsetName, String responseCharsetName, String contentType) throws Exception {

    HttpClient httpclient = new HttpClient();

    HttpMethod request_method = null;
    HTTPResponse responseData = new HTTPResponse();
    NameValuePair[] names_values = null;

    String requestContentType;
    if (contentType != null && contentType.length() > 0) {
        requestContentType = contentType;
    } else {
        requestContentType = DEFAULT_CONTENT_TYPE;
    }

    if (parameters != null && method.equals("PUT") == false) {
        names_values = new NameValuePair[parameters.length];

        for (int i = 0; i < parameters.length; i++) {
            names_values[i] = new NameValuePair(parameters[i][0], parameters[i][1]);
        }

    }
    if (method.equalsIgnoreCase("POST")) {
        request_method = new PostMethod(url.toString());
        if (names_values != null)
            ((PostMethod) request_method).setRequestBody(names_values);
    } else if (method.equalsIgnoreCase("PUT")) {
        if (parameters == null)
            throw new Exception("No data to use in PUT request");
        request_method = new PutMethod(url.toString());
        StringRequestEntity sre = new StringRequestEntity(parameters[0][0]);
        ((PutMethod) request_method).setRequestEntity(sre);
    } else if (method.equalsIgnoreCase("SOAP")) {
        String urlString = url.toString() + "?";
        String message = null;
        String action = null;
        for (int i = 0; i < parameters.length; i++) {

            if (parameters[i][0].equals(SOAPMESSAGE))
                message = parameters[i][1];
            else if (parameters[i][0].equals(SOAP_ACTION_HEADER))
                action = parameters[i][1];
            else
                urlString += parameters[i][0] + "=" + parameters[i][1] + "&";
        }
        urlString = urlString.substring(0, urlString.length() - 1);
        request_method = new PostMethod(urlString);
        // Encoding content with requested charset 
        StringRequestEntity sre = new StringRequestEntity(message, requestContentType, charsetName);
        ((PostMethod) request_method).setRequestEntity(sre);
        if (action != null) {
            request_method.setRequestHeader(SOAP_ACTION_HEADER, action);
        }
        // Adding charset also into header's Content-Type
        request_method.addRequestHeader(CONTENT_TYPE_HEADER, requestContentType + "; charset=" + charsetName);
    } else {
        request_method = new GetMethod(url.toString());
        if (names_values != null)
            ((GetMethod) request_method).setQueryString(names_values);
    }

    user = (user == null || user.length() < 1) ? null : user;
    password = (password == null || password.length() < 1) ? null : password;

    if ((user != null & password == null) || (user == null & password != null)) {
        throw new Exception("Invalid username or password");

    }
    if (user != null && password != null) {
        httpclient.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
        httpclient.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM),
                defaultcreds);
        request_method.setDoAuthentication(true);
    }

    try {
        httpclient.executeMethod(request_method);

        if (request_method.getStatusCode() != HttpStatus.SC_OK) {
            responseData
                    .setResponseError(request_method.getStatusCode() + " " + request_method.getStatusText());
        }

        //Write response header to the out string array
        Header[] headers = request_method.getResponseHeaders();
        responseData.appendToHeaders("\nHTTP status " + request_method.getStatusCode() + "\n");
        for (int i = 0; i < headers.length; i++) {
            responseData.appendToHeaders(headers[i].getName() + ": " + headers[i].getValue() + "\n");
        }

        /*
         * TODO: By default, the response charset should be read from the Content-Type header of 
         * the response and that should be used in the InputStreamReader constructor: 
         * 
         * <code>new InputStreamReader(request_method.getResponseBodyAsStream(), 
         *                   ((HttpMethodBase)request_method).getResponseCharSet());</code>
         * 
         * But for backwards compatibility, the charset used by default is now the one that the 
         * HttpClient library chooses (ISO-8859-1). An alternative charset can be chosen, but in 
         * no situation is the charset read from the response's Content-Type header.
         */
        BufferedReader br = null;
        if (responseCharsetName != null) {
            br = new BufferedReader(
                    new InputStreamReader(request_method.getResponseBodyAsStream(), responseCharsetName));
        } else {
            br = new BufferedReader(new InputStreamReader(request_method.getResponseBodyAsStream()));
        }

        String responseline;
        //Write response body to the out string array
        while ((responseline = br.readLine()) != null) {
            responseData.appendToBody(responseline + "\n");
        }
    } finally {
        request_method.releaseConnection();
    }
    return responseData;
}