Example usage for org.apache.http.message AbstractHttpMessage addHeader

List of usage examples for org.apache.http.message AbstractHttpMessage addHeader

Introduction

In this page you can find the example usage for org.apache.http.message AbstractHttpMessage addHeader.

Prototype

public void addHeader(String str, String str2) 

Source Link

Usage

From source file:org.stem.api.BaseHttpClient.java

protected static void setHeaders(AbstractHttpMessage request) {
    request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
    request.addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString());
}

From source file:com.threatconnect.sdk.conn.ConnectionUtil.java

static void applyHeaders(Configuration config, AbstractHttpMessage message, String httpMethod, String urlPath,
        String contentType, String acceptType) {
    if (config.getTcApiToken() != null) {
        message.addHeader("authorization", "TC-Token " + config.getTcApiToken());
    } else {/* ww w . j  a  v  a  2 s .c  o m*/
        Long ts = System.currentTimeMillis() / 1000L;
        String sig = getSignature(ts, httpMethod, urlPath, null);
        String hmacSig = getHmacSha256Signature(sig, config.getTcApiUserSecretKey());
        String auth = getAuthorizationText(config, hmacSig);

        message.addHeader("timestamp", "" + ts);
        message.addHeader("authorization", auth);
    }

    message.addHeader("Accept", acceptType);
    if (contentType != null) {
        message.addHeader("Content-Type", contentType);
    }
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

/**
 * Add a consistent set of HTTP headers to all requests.
 * @param msg An HTTP message/*from w ww .  j  a  v  a  2s . com*/
 */
private static void addHttpHeaders(AbstractHttpMessage msg) {
    msg.addHeader(HttpHeaders.USER_AGENT, "VirtMus-" + MainApp.VERSION);
    msg.setHeader("X-VirtMus-ID", String.valueOf(MainApp.getInstallId()));
}

From source file:com.logsniffer.event.publisher.http.HttpPublisher.java

protected void httpAddons(final AbstractHttpMessage httpMessage, final Event event) {
    if (headers != null) {
        for (String headerKey : headers.keySet()) {
            httpMessage.addHeader(headerKey, headers.get(headerKey));
        }//from   ww  w  . j ava  2  s  .  c om
    }
}

From source file:com.touchsi.sutee.android.rest.RestClient.java

private void addHeaders(AbstractHttpMessage request) {
    for (NameValuePair h : headers) {
        request.addHeader(h.getName(), h.getValue());
    }//from   ww w .j a  v a  2 s  .  c  o m
}

From source file:org.dasein.cloud.opsource.OpSourceMethod.java

public Document invoke() throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + OpSource.class.getName() + ".invoke()");
    }// w  w  w  .  j  a  v  a2  s . c om
    try {
        URL url = null;
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e1) {
            throw new CloudException(e1);
        }
        final String host = url.getHost();
        final int urlPort = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
        final String urlStr = url.toString();

        DefaultHttpClient httpclient = new DefaultHttpClient();

        /**  HTTP Authentication */
        String uid = new String(provider.getContext().getAccessPublic());
        String pwd = new String(provider.getContext().getAccessPrivate());

        /** Type of authentication */
        List<String> authPrefs = new ArrayList<String>(2);
        authPrefs.add(AuthPolicy.BASIC);

        httpclient.getParams().setParameter("http.auth.scheme-pref", authPrefs);
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(host, urlPort, null),
                new UsernamePasswordCredentials(uid, pwd));

        if (wire.isDebugEnabled()) {
            wire.debug("--------------------------------------------------------------> " + urlStr);
            wire.debug("");
        }

        AbstractHttpMessage method = this.getMethod(parameters.get(OpSource.HTTP_Method_Key), urlStr);
        method.setParams(new BasicHttpParams().setParameter(urlStr, url));
        /**  Set headers */
        method.addHeader(OpSource.Content_Type_Key, parameters.get(OpSource.Content_Type_Key));

        /** POST/PUT method specific logic */
        if (method instanceof HttpEntityEnclosingRequest) {
            HttpEntityEnclosingRequest entityEnclosingMethod = (HttpEntityEnclosingRequest) method;
            String requestBody = parameters.get(OpSource.HTTP_Post_Body_Key);

            if (requestBody != null) {
                if (wire.isDebugEnabled()) {
                    wire.debug(requestBody);
                }

                AbstractHttpEntity entity = new ByteArrayEntity(requestBody.getBytes());
                entity.setContentType(parameters.get(OpSource.Content_Type_Key));
                entityEnclosingMethod.setEntity(entity);
            } else {
                throw new CloudException("The request body is null for a post request");
            }
        }

        /** Now parse the xml */
        try {

            HttpResponse httpResponse;
            int status;
            if (wire.isDebugEnabled()) {
                for (org.apache.http.Header header : method.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
            }
            /**  Now execute the request */
            APITrace.trace(provider, method.toString() + " " + urlStr);
            httpResponse = httpclient.execute((HttpUriRequest) method);
            status = httpResponse.getStatusLine().getStatusCode();
            if (wire.isDebugEnabled()) {
                wire.debug("invoke(): HTTP Status " + httpResponse.getStatusLine().getStatusCode() + " "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            org.apache.http.Header[] headers = httpResponse.getAllHeaders();

            HttpEntity entity = httpResponse.getEntity();
            if (wire.isDebugEnabled()) {
                wire.debug("HTTP xml status code ---------" + status);
                for (org.apache.http.Header h : headers) {
                    if (h.getValue() != null) {
                        wire.debug(h.getName() + ": " + h.getValue().trim());
                    } else {
                        wire.debug(h.getName() + ":");
                    }
                }
                /** Can not enable this line, otherwise the entity would be empty*/
                // wire.debug("OpSource Response Body for request " + urlStr + " = " + EntityUtils.toString(entity));
                wire.debug("-----------------");
            }
            if (entity == null) {
                parseError(status, "Empty entity");
            }

            String responseBody = EntityUtils.toString(entity);

            if (status == HttpStatus.SC_OK) {
                InputStream input = null;
                try {
                    input = new ByteArrayInputStream(responseBody.getBytes("UTF-8"));
                    if (input != null) {
                        Document doc = null;
                        try {
                            doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);
                            if (wire.isDebugEnabled()) {
                                try {
                                    TransformerFactory transfac = TransformerFactory.newInstance();
                                    Transformer trans = transfac.newTransformer();
                                    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                    trans.setOutputProperty(OutputKeys.INDENT, "yes");

                                    StringWriter sw = new StringWriter();
                                    StreamResult result = new StreamResult(sw);
                                    DOMSource source = new DOMSource(doc);
                                    trans.transform(source, result);
                                    String xmlString = sw.toString();
                                    wire.debug(xmlString);
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            logger.debug(ex.toString(), ex);
                        }
                        return doc;
                    }
                } catch (IOException e) {
                    logger.error(
                            "invoke(): Failed to read xml error due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                /*
                catch( SAXException e ) {
                throw new CloudException(e);
                }                    
                catch( ParserConfigurationException e ) {
                throw new InternalException(e);
                }
                */
            } else if (status == HttpStatus.SC_NOT_FOUND) {
                throw new CloudException("An internal error occured: The endpoint was not found");
            } else {
                if (responseBody != null) {
                    parseError(status, responseBody);
                    Document parsedError = null;
                    if (!responseBody.contains("<HR")) {
                        parsedError = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                                .parse(new ByteArrayInputStream(responseBody.getBytes("UTF-8")));
                        if (wire.isDebugEnabled()) {
                            try {
                                TransformerFactory transfac = TransformerFactory.newInstance();
                                Transformer trans = transfac.newTransformer();
                                trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                trans.setOutputProperty(OutputKeys.INDENT, "yes");

                                StringWriter sw = new StringWriter();
                                StreamResult result = new StreamResult(sw);
                                DOMSource source = new DOMSource(parsedError);
                                trans.transform(source, result);
                                String xmlString = sw.toString();
                                wire.debug(xmlString);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    } else
                        logger.debug("Error message was unparsable");
                    return parsedError;
                }
            }
        } catch (ParseException e) {
            throw new CloudException(e);
        } catch (SAXException e) {
            throw new CloudException(e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CloudException(e);
        } catch (ParserConfigurationException e) {
            throw new CloudException(e);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + OpSource.class.getName() + ".invoke()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------------> " + endpoint);
        }
    }
    return null;
}

From source file:com.att.api.rest.RESTClient.java

/**
 * Sets headers to the http message./*  ww  w  .  j  a v  a 2  s .co m*/
 *
 * @param httpMsg http message to set headers for
 */
private void addInternalHeaders(AbstractHttpMessage httpMsg) {
    if (headers.isEmpty()) {
        return;
    }

    final Set<String> keySet = headers.keySet();
    for (final String key : keySet) {
        final List<String> values = headers.get(key);
        for (final String value : values) {
            httpMsg.addHeader(key, value);
        }
    }
}

From source file:org.jkan997.slingbeans.slingfs.FileSystemServer.java

private void configureAuth(AbstractHttpMessage method) {
    try {/*from  www .  j  av a  2 s  .com*/
        String authString = name + ":" + password;
        LogHelper.logInfo(this, "auth string: " + authString);
        String authStringEnc = Base64.encodeBytes(authString.getBytes());
        LogHelper.logInfo(this, "Base64 encoded auth string: " + authStringEnc);
        method.addHeader("Authorization", "Basic " + authStringEnc);
        //method.addHeader(new BasicScheme().authenticate(credentials, (HttpRequest) method));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.emc.esu.api.rest.EsuRestApiApache.java

private void setHeaders(AbstractHttpMessage request, Map<String, String> headers) {
    for (String headerName : headers.keySet()) {
        request.addHeader(headerName, headers.get(headerName));
    }/*from w  ww. j  ava 2  s .c  o  m*/
}