Example usage for org.apache.http.client.methods HttpRequestBase setHeader

List of usage examples for org.apache.http.client.methods HttpRequestBase setHeader

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpRequestBase setHeader.

Prototype

public void setHeader(String str, String str2) 

Source Link

Usage

From source file:eu.vital.TrustManager.connectors.ppi.PPIManager.java

private String query(String ppi_endpoint, String body, String method)
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    Cookie ck;//from   w w w . jav a 2s.  c o m
    //String internalToken;
    CloseableHttpClient httpclient;
    HttpRequestBase httpaction;
    //boolean wasEmpty;
    //int code;
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

    httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    //httpclient = HttpClients.createDefault();

    URI uri = null;
    try {
        // Prepare to forward the request to the proxy
        uri = new URI(ppi_endpoint);
    } catch (URISyntaxException e1) {
        //log
    }

    if (method.equals("GET")) {
        httpaction = new HttpGet(uri);
    } else {
        httpaction = new HttpPost(uri);
    }

    // Get token or authenticate if null or invalid
    //internalToken = client.getToken();
    ck = new Cookie("vitalAccessToken", cookie.substring(17));

    httpaction.setHeader("Cookie", ck.toString());
    httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(3000).setConnectTimeout(3000)
            .setSocketTimeout(3000).build());
    httpaction.setHeader("Content-Type", javax.ws.rs.core.MediaType.APPLICATION_JSON);
    StringEntity strEntity = new StringEntity(body, StandardCharsets.UTF_8);
    if (method.equals("POST")) {
        ((HttpPost) httpaction).setEntity(strEntity);
    }

    // Execute and get the response.
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpaction);
    } catch (ClientProtocolException e) {
        java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, e);
    } catch (IOException e) {
        try {
            // Try again with a higher timeout
            try {
                Thread.sleep(1000); // do not retry immediately
            } catch (InterruptedException e1) {
                // e1.printStackTrace();
            }
            httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(7000)
                    .setConnectTimeout(7000).setSocketTimeout(7000).build());
            response = httpclient.execute(httpaction);
        } catch (ClientProtocolException ea) {
            java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, ea);
            return "";
        } catch (IOException ea) {
            try {
                // Try again with a higher timeout
                try {
                    Thread.sleep(1000); // do not retry immediately
                } catch (InterruptedException e1) {
                    java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, e1);
                    return "";
                }
                httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(12000)
                        .setConnectTimeout(12000).setSocketTimeout(12000).build());
                response = httpclient.execute(httpaction);
            } catch (ClientProtocolException eaa) {
                java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, eaa);
                return "";
            } catch (Exception eaa) {
                java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, eaa);
                return "";
                //return eaa.getMessage();
            }
        }
    }

    int statusCode;
    try {
        statusCode = response.getStatusLine().getStatusCode();
    } catch (Exception eaa) {
        java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, eaa);
        return "";
    }

    if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) {
        if (statusCode == 503) {
            java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, "PPI 503");
            return "";
        } else if (statusCode == 502) {
            java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, "PPI 502");
            return "";
        } else if (statusCode == 401) {
            java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, "PPI 401");
            return "";
        } else {
            java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, "PPI 500");
            return "";
            //throw new ServiceUnavailableException();
        }
    }

    HttpEntity entity;
    entity = response.getEntity();
    String respString = "";

    if (entity != null) {
        try {
            respString = EntityUtils.toString(entity);
            response.close();
            return respString;
        } catch (ParseException | IOException e) {
            java.util.logging.Logger.getLogger(PPIManager.class.getName()).log(Level.SEVERE, null, "PPI 401");
            return "";
        }
    }
    return respString;

}

From source file:in.huohua.peterson.network.NetworkUtils.java

public static HttpResponse httpQuery(final HttpRequest request) throws ClientProtocolException, IOException {
    final HttpRequestBase requestBase;
    if (request.getHttpMethod().equals(HttpRequest.HTTP_METHOD_GET)) {
        final StringBuilder builder = new StringBuilder(request.getUrl());
        if (request.getParams() != null) {
            if (!request.getUrl().contains("?")) {
                builder.append("?");
            } else {
                builder.append("&");
            }/*from ww  w.j av a 2 s.c  om*/
            builder.append(request.getParamsAsString());
        }
        final HttpGet get = new HttpGet(builder.toString());
        requestBase = get;
    } else if (request.getHttpMethod().equals(HttpRequest.HTTP_METHOD_POST)) {
        final HttpPost post = new HttpPost(request.getUrl());
        if (request.getEntity() != null) {
            post.setEntity(request.getEntity());
        } else {
            post.setEntity(new UrlEncodedFormEntity(request.getParamsAsList(), "UTF-8"));
        }
        requestBase = post;
    } else if (request.getHttpMethod().equals(HttpRequest.HTTP_METHOD_PUT)) {
        final HttpPut put = new HttpPut(request.getUrl());
        if (request.getEntity() != null) {
            put.setEntity(request.getEntity());
        } else {
            put.setEntity(new UrlEncodedFormEntity(request.getParamsAsList(), "UTF-8"));
        }
        requestBase = put;
    } else if (request.getHttpMethod().equals(HttpRequest.HTTP_METHOD_DELETE)) {
        final StringBuilder builder = new StringBuilder(request.getUrl());
        if (request.getParams() != null) {
            if (!request.getUrl().contains("?")) {
                builder.append("?");
            } else {
                builder.append("&");
            }
            builder.append(request.getParamsAsString());
        }
        final HttpDelete delete = new HttpDelete(builder.toString());
        requestBase = delete;
    } else {
        return null;
    }

    if (request.getHeaders() != null) {
        final Iterator<Map.Entry<String, String>> iterator = request.getHeaders().entrySet().iterator();
        while (iterator.hasNext()) {
            final Map.Entry<String, String> kv = iterator.next();
            requestBase.setHeader(kv.getKey(), kv.getValue());
        }
    }
    return HTTP_CLIENT.execute(requestBase);
}

From source file:com.evolveum.polygon.connector.drupal.DrupalConnector.java

protected JSONArray callRequest(HttpRequestBase request) throws IOException {
    LOG.ok("request URI: {0}", request.getURI());
    request.setHeader("Content-Type", CONTENT_TYPE);

    authHeader(request);//from   w w w . ja v a2  s  .co  m

    CloseableHttpResponse response = execute(request);
    LOG.ok("response: {0}", response);
    processDrupalResponseErrors(response);

    String result = EntityUtils.toString(response.getEntity());
    LOG.ok("response body: {0}", result);
    closeResponse(response);
    return new JSONArray(result);
}

From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java

private String queryWithExceptions(String dms_endpoint, String body, String method)
        throws SocketTimeoutException, ConnectException, IOException, InterruptedException {
    Cookie ck;//w  ww.  ja  v a 2 s . c  o m
    //String internalToken;
    CloseableHttpClient httpclient;
    HttpRequestBase httpaction;
    //boolean wasEmpty;
    //int code;

    httpclient = HttpClients.createDefault();

    URI uri = null;
    try {
        // Prepare to forward the request to the proxy
        uri = new URI(dms_URL + "/" + dms_endpoint);
    } catch (URISyntaxException e1) {
        java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1);
    }

    if (method.equals("GET")) {
        httpaction = new HttpGet(uri);
    } else {
        httpaction = new HttpPost(uri);
    }

    // Get token or authenticate if null or invalid
    //internalToken = client.getToken();
    ck = new Cookie("vitalAccessToken", cookie.substring(17));

    httpaction.setHeader("Cookie", ck.toString());
    httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000)
            .setSocketTimeout(5000).build());
    httpaction.setHeader("Content-Type", javax.ws.rs.core.MediaType.APPLICATION_JSON);

    StringEntity strEntity = new StringEntity(body, StandardCharsets.UTF_8);

    if (method.equals("POST")) {
        ((HttpPost) httpaction).setEntity(strEntity);
    }

    // Execute and get the response.
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpaction);
    } catch (ClientProtocolException e) {
        throw new ClientProtocolException();
    } catch (IOException e) {
        try {
            // Try again with a higher timeout
            try {
                Thread.sleep(1000); // do not retry immediately
            } catch (InterruptedException e1) {
                throw new InterruptedException();
                // e1.printStackTrace();
            }
            httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(7000)
                    .setConnectTimeout(7000).setSocketTimeout(7000).build());
            response = httpclient.execute(httpaction);
        } catch (ClientProtocolException ea) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, ea);
            throw new ClientProtocolException();
        } catch (IOException ea) {
            try {
                // Try again with a higher timeout
                try {
                    Thread.sleep(1000); // do not retry immediately
                } catch (InterruptedException e1) {
                    java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1);
                    throw new InterruptedException();
                }
                httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(12000)
                        .setConnectTimeout(12000).setSocketTimeout(12000).build());
                response = httpclient.execute(httpaction);
            } catch (ClientProtocolException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                throw new ClientProtocolException();
            } catch (SocketTimeoutException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                throw new SocketTimeoutException();
            } catch (ConnectException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                throw new ConnectException();
            } catch (ConnectTimeoutException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                throw new ConnectTimeoutException();
            }
        }
    }

    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) {
        if (statusCode == 503) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "httpStatusCode 503");
            throw new ServiceUnavailableException();
        } else if (statusCode == 502) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "httpStatusCode 502");
            throw new ServerErrorException(502);
        } else if (statusCode == 401) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "could't Athorize the DMS");
            throw new NotAuthorizedException("could't Athorize the DMS");
        } else {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "httpStatusCode 500");
            throw new ServiceUnavailableException();
        }
    }

    HttpEntity entity;
    entity = response.getEntity();
    String respString = "";

    if (entity != null) {
        try {
            respString = EntityUtils.toString(entity);
            response.close();
        } catch (ParseException | IOException e) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e);
        }
    }
    return respString;

}

From source file:ch.iterate.openstack.swift.Client.java

private Response execute(final HttpRequestBase method) throws IOException {
    try {// ww  w.j  av a  2 s  .com
        method.setHeader(Constants.X_AUTH_TOKEN, authenticationResponse.getAuthToken());
        try {
            return new DefaultResponseHandler().handleResponse(client.execute(method));
        } catch (AuthorizationException e) {
            method.abort();
            authenticationResponse = this.authenticate();
            method.reset();
            // Add new auth token retrieved
            method.setHeader(Constants.X_AUTH_TOKEN, authenticationResponse.getAuthToken());
            // Retry
            return new DefaultResponseHandler().handleResponse(client.execute(method));
        }
    } catch (IOException e) {
        // In case of an IOException the connection will be released back to the connection manager automatically
        method.abort();
        throw e;
    }
}

From source file:com.evolveum.polygon.connector.drupal.DrupalConnector.java

protected JSONObject callRequest(HttpRequestBase request, boolean parseResult) throws IOException {
    LOG.ok("request URI: {0}", request.getURI());
    request.setHeader("Content-Type", CONTENT_TYPE);

    authHeader(request);//from ww  w.jav  a  2  s . c  om

    CloseableHttpResponse response = null;
    response = execute(request);
    LOG.ok("response: {0}", response);
    processDrupalResponseErrors(response);

    if (!parseResult) {
        closeResponse(response);
        return null;
    }
    String result = EntityUtils.toString(response.getEntity());
    LOG.ok("response body: {0}", result);
    closeResponse(response);
    return new JSONObject(result);
}

From source file:at.orz.arangodb.http.HttpManager.java

/**
 * /* w  w  w .j  a v  a 2 s.  c  o m*/
 * @param requestEntity
 * @return
 * @throws ArangoException
 */
public HttpResponseEntity execute(HttpRequestEntity requestEntity) throws ArangoException {

    String url = buildUrl(requestEntity);

    if (logger.isDebugEnabled()) {
        if (requestEntity.type == RequestType.POST || requestEntity.type == RequestType.PUT
                || requestEntity.type == RequestType.PATCH) {
            logger.debug("[REQ]http-{}: url={}, headers={}, body={}",
                    new Object[] { requestEntity.type, url, requestEntity.headers, requestEntity.bodyText });
        } else {
            logger.debug("[REQ]http-{}: url={}, headers={}",
                    new Object[] { requestEntity.type, url, requestEntity.headers });
        }
    }

    HttpRequestBase request = null;
    switch (requestEntity.type) {
    case GET:
        request = new HttpGet(url);
        break;
    case POST:
        HttpPost post = new HttpPost(url);
        configureBodyParams(requestEntity, post);
        request = post;
        break;
    case PUT:
        HttpPut put = new HttpPut(url);
        configureBodyParams(requestEntity, put);
        request = put;
        break;
    case PATCH:
        HttpPatch patch = new HttpPatch(url);
        configureBodyParams(requestEntity, patch);
        request = patch;
        break;
    case HEAD:
        request = new HttpHead(url);
        break;
    case DELETE:
        request = new HttpDelete(url);
        break;
    }

    // common-header
    String userAgent = "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.0; +http://mt.orz.at/)"; // TODO: 
    request.setHeader("User-Agent", userAgent);
    //request.setHeader("Content-Type", "binary/octet-stream");

    // optinal-headers
    if (requestEntity.headers != null) {
        for (Entry<String, Object> keyValue : requestEntity.headers.entrySet()) {
            request.setHeader(keyValue.getKey(), keyValue.getValue().toString());
        }
    }

    // Basic Auth
    Credentials credentials = null;
    if (requestEntity.username != null && requestEntity.password != null) {
        credentials = new UsernamePasswordCredentials(requestEntity.username, requestEntity.password);
    } else if (configure.getUser() != null && configure.getPassword() != null) {
        credentials = new UsernamePasswordCredentials(configure.getUser(), configure.getPassword());
    }
    if (credentials != null) {
        request.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false));
    }

    // CURL/httpie Logger
    if (configure.isEnableCURLLogger()) {
        CURLLogger.log(url, requestEntity, userAgent, credentials);
    }

    HttpResponse response = null;
    try {

        response = client.execute(request);
        if (response == null) {
            return null;
        }

        HttpResponseEntity responseEntity = new HttpResponseEntity();

        // http status
        StatusLine status = response.getStatusLine();
        responseEntity.statusCode = status.getStatusCode();
        responseEntity.statusPhrase = status.getReasonPhrase();

        logger.debug("[RES]http-{}: statusCode={}", requestEntity.type, responseEntity.statusCode);

        // ??
        //// TODO etag???
        Header etagHeader = response.getLastHeader("etag");
        if (etagHeader != null) {
            responseEntity.etag = Long.parseLong(etagHeader.getValue().replace("\"", ""));
        }
        // Map???
        responseEntity.headers = new TreeMap<String, String>();
        for (Header header : response.getAllHeaders()) {
            responseEntity.headers.put(header.getName(), header.getValue());
        }

        // ???
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            Header contentType = entity.getContentType();
            if (contentType != null) {
                responseEntity.contentType = contentType.getValue();
                if (responseEntity.isDumpResponse()) {
                    responseEntity.stream = entity.getContent();
                    logger.debug("[RES]http-{}: stream, {}", requestEntity.type, contentType.getValue());
                }
            }
            // Close stream in this method.
            if (responseEntity.stream == null) {
                responseEntity.text = IOUtils.toString(entity.getContent());
                logger.debug("[RES]http-{}: text={}", requestEntity.type, responseEntity.text);
            }
        }

        return responseEntity;

    } catch (ClientProtocolException e) {
        throw new ArangoException(e);
    } catch (IOException e) {
        throw new ArangoException(e);
    }

}

From source file:org.apache.nifi.remote.util.SiteToSiteRestApiClient.java

private void setHandshakeProperties(final HttpRequestBase httpRequest) {
    if (compress) {
        httpRequest.setHeader(HANDSHAKE_PROPERTY_USE_COMPRESSION, "true");
    }/*www .ja v a2  s  . c  o m*/

    if (requestExpirationMillis > 0) {
        httpRequest.setHeader(HANDSHAKE_PROPERTY_REQUEST_EXPIRATION, String.valueOf(requestExpirationMillis));
    }

    if (batchCount > 0) {
        httpRequest.setHeader(HANDSHAKE_PROPERTY_BATCH_COUNT, String.valueOf(batchCount));
    }

    if (batchSize > 0) {
        httpRequest.setHeader(HANDSHAKE_PROPERTY_BATCH_SIZE, String.valueOf(batchSize));
    }

    if (batchDurationMillis > 0) {
        httpRequest.setHeader(HANDSHAKE_PROPERTY_BATCH_DURATION, String.valueOf(batchDurationMillis));
    }
}

From source file:ch.iterate.openstack.swift.Client.java

private <T> T execute(final HttpRequestBase method, ResponseHandler<T> handler) throws IOException {
    try {/*from  w ww  . j a v a2  s .  c o m*/
        method.setHeader(Constants.X_AUTH_TOKEN, authenticationResponse.getAuthToken());
        try {
            return client.execute(method, handler);
        } catch (AuthorizationException e) {
            method.abort();
            authenticationResponse = this.authenticate();
            method.reset();
            // Add new auth token retrieved
            method.setHeader(Constants.X_AUTH_TOKEN, authenticationResponse.getAuthToken());
            // Retry
            return client.execute(method, handler);
        }
    } catch (IOException e) {
        // In case of an IOException the connection will be released back to the connection manager automatically
        method.abort();
        throw e;
    } finally {
        method.reset();
    }
}

From source file:synapticloop.scaleway.api.ScalewayApiClient.java

private HttpRequestBase buildRequest(String httpMethod, String requestPath, Object entityContent)
        throws ScalewayApiException {
    LOGGER.debug("Building request for method '{}' and URL '{}'", httpMethod, requestPath);

    HttpRequestBase request = null;
    switch (httpMethod) {
    case Constants.HTTP_METHOD_GET:
        request = new HttpGet(requestPath);
        break;/*w w  w. j  av a 2  s . c  o m*/
    case Constants.HTTP_METHOD_POST:
        request = new HttpPost(requestPath);
        break;
    case Constants.HTTP_METHOD_DELETE:
        request = new HttpDelete(requestPath);
        break;
    case Constants.HTTP_METHOD_PATCH:
        request = new HttpPatch(requestPath);
        break;
    case Constants.HTTP_METHOD_PUT:
        request = new HttpPut(requestPath);
        break;
    }

    request.setHeader(Constants.HEADER_KEY_AUTH_TOKEN, accessToken);
    request.setHeader(HttpHeaders.CONTENT_TYPE, Constants.HEADER_VALUE_JSON_APPLICATION);

    if (null != entityContent) {
        if (request instanceof HttpEntityEnclosingRequestBase) {
            try {
                StringEntity entity = new StringEntity(serializeObject(entityContent));
                ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
            } catch (UnsupportedEncodingException | JsonProcessingException ex) {
                throw new ScalewayApiException(ex);
            }
        } else {
            LOGGER.error("Attempting to set entity on non applicable base class of '{}'", request.getClass());
        }
    }
    return request;
}