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

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

Introduction

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

Prototype

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

Source Link

Usage

From source file:org.eclipse.ecf.remoteservice.rest.client.RestClientService.java

protected void addRequestHeaders(HttpMethod httpMethod, IRemoteCall call, IRemoteCallable callable) {
    // Add request headers from the callable
    Map requestHeaders = (callable.getRequestType() instanceof AbstractRequestType)
            ? ((AbstractRequestType) callable.getRequestType()).getDefaultRequestHeaders()
            : new HashMap();
    if (requestHeaders == null)
        requestHeaders = new HashMap();

    if (call instanceof IRestCall) {
        Map callHeaders = ((IRestCall) call).getRequestHeaders();
        if (callHeaders != null)
            requestHeaders.putAll(requestHeaders);
    }/*w w  w  . j  a va  2s  .  c  o m*/

    Set keySet = requestHeaders.keySet();
    Object[] headers = keySet.toArray();
    for (int i = 0; i < headers.length; i++) {
        String key = (String) headers[i];
        String value = (String) requestHeaders.get(key);
        httpMethod.addRequestHeader(key, value);
    }
}

From source file:org.eclipse.om2m.comm.http.RestHttpClient.java

/**
* Converts a protocol-independent {@link RequestIndication} object into a standard HTTP request and sends a standard HTTP request.
* Converts the received standard HTTP request into {@link ResponseConfirm} object and returns it back.
* @param requestIndication - protocol independent request.
* @return protocol independent response.
*///  w  w w.  j  a va2s. c o  m
public ResponseConfirm sendRequest(RequestIndication requestIndication) {

    logServiceTracker = new ServiceTracker(FrameworkUtil.getBundle(RestHttpClient.class).getBundleContext(),
            org.osgi.service.log.LogService.class.getName(), null);
    logServiceTracker.open();
    logservice = (LogService) logServiceTracker.getService();
    LOGGER.debug("Http Client > " + requestIndication);
    logservice.log(LogService.LOG_ERROR, "Http Client > " + requestIndication);

    HttpClient httpclient = new HttpClient();

    ResponseConfirm responseConfirm = new ResponseConfirm();
    HttpMethod httpMethod = null;
    String url = requestIndication.getUrl();
    if (!url.startsWith(protocol + "://")) {
        url = protocol + "://" + url;
    }
    try {
        switch (requestIndication.getMethod()) {
        case "RETRIEVE":
            httpMethod = new GetMethod(url);
            break;
        case "CREATE":
            httpMethod = new PostMethod(url);

            ((PostMethod) httpMethod).setRequestEntity(
                    new StringRequestEntity(requestIndication.getRepresentation(), "application/xml", "UTF8"));
            break;
        case "UPDATE":
            httpMethod = new PutMethod(url);
            ((PutMethod) httpMethod).setRequestEntity(
                    new StringRequestEntity(requestIndication.getRepresentation(), "application/xml", "UTF8"));
            break;
        case "DELETE":
            httpMethod = new DeleteMethod(url);
            break;
        case "EXECUTE":
            httpMethod = new PostMethod(url);
            break;
        default:
            return new ResponseConfirm();
        }
        httpMethod.addRequestHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64(requestIndication.getRequestingEntity().getBytes())));
        httpMethod.setQueryString(getQueryFromParams(requestIndication.getParameters()));

        int statusCode = httpclient.executeMethod(httpMethod);
        responseConfirm.setStatusCode(getRestStatusCode(statusCode));

        if (statusCode != 204) {
            if (httpMethod.getResponseBody() != null) {
                responseConfirm.setRepresentation(new String(httpMethod.getResponseBody()));
            }
        }
        if (statusCode == 201) {
            if (httpMethod.getResponseHeader("Location").getValue() != null) {
                responseConfirm.setResourceURI(httpMethod.getResponseHeader("Location").getValue());
            }
        }
        //LOGGER.debug("Http Client > "+responseConfirm);
        LOGGER.debug("Http Client > " + responseConfirm);
        logservice.log(LogService.LOG_ERROR, "Http Client > " + responseConfirm);

    } catch (IOException e) {
        LOGGER.error(url + " Not Found" + responseConfirm, e);
        logservice.log(LogService.LOG_ERROR, url + " Not Found" + responseConfirm);

    } finally {
        httpMethod.releaseConnection();
    }

    return responseConfirm;
}

From source file:org.entando.entando.plugins.jpoauthclient.aps.system.httpclient.OAuthHttpClient.java

@Override
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  ava2s . 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 = this._clientPool.getHttpClient(new URL(httpMethod.getURI().toString()));
    client.executeMethod(httpMethod);
    return new HttpMethodResponse(httpMethod, excerpt, request.getContentCharset());
}

From source file:org.everit.jira.updatenotifier.TimetrackerVersionUpdater.java

private synchronized void update() {
    if (!updateRequired()) {
        return;/* w w  w . ja  v a  2 s.co m*/
    }
    updateNotifier.putLastUpdateTime(System.currentTimeMillis());
    HttpClient httpClient = new HttpClient();
    HttpMethod method = new GetMethod(
            MARKETPLACE_URL_FIRST_PART + buildNumber + MARKETPLACE_URL_WITH_VERSION_PARAMETER);
    method.addRequestHeader("accept", "application/json");
    String response;
    try {
        int statusCode = httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new UpdateException("Update JTTP latest version failed. Status code is : " + statusCode
                    + "Response body is: " + method.getResponseBodyAsString());
        }
        response = method.getResponseBodyAsString();
    } catch (IOException e) {
        throw new UpdateException("Update JTTP latest version failed. ", e);
    }
    Gson gson = new Gson();
    JiraMarketplaceJSONDTO fromJson = gson.fromJson(response, JiraMarketplaceJSONDTO.class);
    String latestVersion = fromJson.getEmbedded().getVersion().getName();
    updateNotifier.putLatestVersion(latestVersion);
}

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

public void doAuthentication(HttpClient client, ProxyRequest request, HttpMethod method, String uid, String pwd)
        throws ProxyAuthenticationException {
    ProxyRequest.OAuth2Config oauthConfig = request.getOauth2Config();
    try {//from ww  w  .  j  a v  a  2  s  . co  m
        OAuthConsumer consumer = newConsumer(oauthConfig.serviceName, oauthConfig, getCallbackURL(request));
        if (oauthConfig.accessToken == null) {
            returnApprovalUrl(request, consumer);
        }

        if (oauthConfig.validityPeriodUTC != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            if (cal.getTimeInMillis() > oauthConfig.validityPeriodUTC) {
                if (oauthConfig.refreshToken == null) {
                    OAuthService.getHandle().deleteOAuth2Token(request.getPortalUid(), oauthConfig.gadgetUrl,
                            oauthConfig.serviceName);
                    returnApprovalUrl(request, consumer);
                } else {
                    log.error(
                            "AccessToken was expired, try re-get the token. [" + oauthConfig.serviceName + "]");
                    getAccessTokenByRefreshToken(request, consumer);
                    OAuth2Token token2 = OAuth2TokenDAO.newInstance().getAccessToken(request.getPortalUid(),
                            oauthConfig.gadgetUrl, oauthConfig.serviceName);
                    oauthConfig.setAccessToken(token2.getAccessToken());
                    oauthConfig.setRefreshToken(token2.getRefreshToken());
                    oauthConfig.setValidityPeriodUTC(token2.getValidityPeriodUTC());
                }
            }
        }

        Map<String, String> parameters = null;
        String contentType = request.getRequestHeader("Content-Type");
        if (contentType != null && contentType.startsWith("application/x-www-form-urlencoded")
                && method.getName().equals("POST")) {
            // TODO analyze charset
            String charset = RequestUtil.getCharset(contentType);
            parameters = RequestUtil.parseRequestBody(request.getRequestBody(), charset);
        }

        if ("Bearer".equalsIgnoreCase(oauthConfig.tokenType)) {
            method.addRequestHeader("Authorization", oauthConfig.tokenType + " " + oauthConfig.accessToken);
        } else {
            method.addRequestHeader("Authorization", "OAuth " + oauthConfig.accessToken);

            String queryString = method.getQueryString();
            queryString = "access_token=" + oauthConfig.accessToken + "&" + queryString;
            method.setQueryString(queryString);
        }
    } catch (URISyntaxException e) {
        throw new ProxyAuthenticationException(e);
    } catch (OAuthException e) {
        throw new ProxyAuthenticationException(e);
    } catch (IOException e) {
        throw new ProxyAuthenticationException(e);
    }
}

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

public void doAuthentication(HttpClient client, ProxyRequest request, HttpMethod method, String uid, String pwd)
        throws ProxyAuthenticationException {
    String uidParamNameHeader = request.getRequestHeader(UID_PARAM_NAME);
    String passwdParamNameHeader = request.getRequestHeader(PASSWD_PARAM_NAME);
    String uidParamName = (uidParamNameHeader != null) ? uidParamNameHeader : this.uidParamName;
    String passwdParamName = (passwdParamNameHeader != null) ? passwdParamNameHeader : this.pwdParamName;
    try {/* w  w  w  .  ja  v  a 2s.c o  m*/
        request.addIgnoreHeader("Content-Type");

        method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
        NameValuePair[] params = new NameValuePair[2];

        PostMethod pMethod = (PostMethod) method;
        String queryString = pMethod.getQueryString();

        // Delete the same parameter's name that has already exist.
        pMethod.removeParameter(uidParamName);
        pMethod.removeParameter(passwdParamName);
        queryString = RequestUtil.removeQueryStringParam(queryString, uidParamName);
        queryString = RequestUtil.removeQueryStringParam(queryString, passwdParamName);

        pMethod.setQueryString(queryString);

        params[0] = new NameValuePair(uidParamName, uid);
        params[1] = new NameValuePair(passwdParamName, pwd);
        pMethod.setRequestBody(params);

        pMethod.addRequestHeader("content-length",
                String.valueOf(pMethod.getRequestEntity().getContentLength()));
    } catch (Exception e) {
        throw new ProxyAuthenticationException(e);
    }
}

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

public void doAuthentication(HttpClient client, ProxyRequest request, HttpMethod method, String uid, String pwd)
        throws ProxyAuthenticationException {
    String uidHeaderNameHeader = request.getRequestHeader(UID_PARAM_NAME);
    String uidHeaderName = (uidHeaderNameHeader != null) ? uidHeaderNameHeader : this.uidHeaderName;
    try {/*from www. ja  va  2s.c om*/
        method.removeRequestHeader(uidHeaderName);
        method.addRequestHeader(uidHeaderName, uid);
    } catch (Exception e) {
        throw new ProxyAuthenticationException(e);
    }
}

From source file:org.jboss.tools.livereload.internal.server.jetty.LiveReloadServerTestCase.java

@Test
public void shouldInjectLiveReloadScriptInHtmlPageWithSimpleAcceptedTypes() throws Exception {
    // pre-condition
    createAndLaunchLiveReloadServer(true);
    final String scriptContent = new StringBuilder(
            "<script>document.write('<script src=\"http://' + location.host.split(':')[0]+ ':")
                    .append(liveReloadServerPort).append("/livereload.js\"></'+ 'script>')</script>")
                    .toString();//from   w ww  .j av a  2 s .  c  om
    // operation
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(indexDocumentlocation);
    method.addRequestHeader("Accept", "text/html");
    int status = client.executeMethod(method);
    // verification
    assertThat(status).isEqualTo(HttpStatus.SC_OK);
    // Read the response body.
    String responseBody = new String(method.getResponseBody());
    assertThat(responseBody).contains(scriptContent);
}

From source file:org.jboss.tools.livereload.internal.server.jetty.LiveReloadServerTestCase.java

@Test
public void shouldInjectLiveReloadScriptInHtmlPageWithSimpleAcceptedTypeAndcharset() throws Exception {
    // pre-condition
    createAndLaunchLiveReloadServer(true);
    final String scriptContent = new StringBuilder(
            "<script>document.write('<script src=\"http://' + location.host.split(':')[0]+ ':")
                    .append(liveReloadServerPort).append("/livereload.js\"></'+ 'script>')</script>")
                    .toString();/*from  w  ww .  j  a va 2  s.  c o m*/
    // operation
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(indexDocumentlocation);
    method.addRequestHeader("Accept", "text/html;charset=UTF-8");
    int status = client.executeMethod(method);
    // verification
    assertThat(status).isEqualTo(HttpStatus.SC_OK);
    // Read the response body.
    String responseBody = new String(method.getResponseBody());
    assertThat(responseBody).contains(scriptContent);
}

From source file:org.jboss.tools.livereload.internal.server.jetty.LiveReloadServerTestCase.java

@Test
public void shouldInjectLiveReloadScriptInHtmlPageWithMultipleAcceptedTypeAndQualityFactors() throws Exception {
    // pre-condition
    createAndLaunchLiveReloadServer(true);
    final String scriptContent = new StringBuilder(
            "<script>document.write('<script src=\"http://' + location.host.split(':')[0]+ ':")
                    .append(liveReloadServerPort).append("/livereload.js\"></'+ 'script>')</script>")
                    .toString();/* ww  w.  j ava  2  s .  c o  m*/
    // operation
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(indexDocumentlocation);
    method.addRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    int status = client.executeMethod(method);
    // verification
    assertThat(status).isEqualTo(HttpStatus.SC_OK);
    // Read the response body.
    String responseBody = new String(method.getResponseBody());
    assertThat(responseBody).contains(scriptContent);
}