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:com.ibm.xsp.extlib.sbt.services.client.SmartCloudService.java

@Override
protected void prepareRequest(HttpClient httpClient, HttpRequestBase httpRequestBase, Args args,
        Content content) throws ClientServicesException {

    Object contents = args.getHandler();
    if (contents instanceof File) {
        String name = args.getParameters().get("file");
        FileEntity fileEnt = new FileEntity((File) contents, getMimeForUpload());
        //fileEnt.setContentEncoding(FORMAT_BINARY);
        httpRequestBase.setHeader("slug", name);
        httpRequestBase.setHeader("Content-type", getMimeForUpload());
        if (fileEnt != null && (httpRequestBase instanceof HttpEntityEnclosingRequestBase)) {
            ((HttpEntityEnclosingRequestBase) httpRequestBase).setEntity(fileEnt);
        }/*from  w ww .j  av a 2  s .  c o  m*/
    }
    // TODO Auto-generated method stub
    super.prepareRequest(httpClient, httpRequestBase, args, content);
}

From source file:com.madrobot.net.HttpTaskHelper.java

/**
 * Add the request header into request/*from   w w w. j av  a 2s  . c  o  m*/
 * 
 * @param httpRequestBase
 *            - base object for http methods
 */
private void setRequestHeaders(HttpRequestBase httpRequestBase) {
    for (String headerName : requestHeader.keySet()) {
        String headerValue = requestHeader.get(headerName);
        httpRequestBase.setHeader(headerName, headerValue);
    }
}

From source file:mobi.jenkinsci.ci.JenkinsCIPlugin.java

protected byte[] retrieveUrl(final String userAgent, final String linkUrl,
        final HashMap<String, HeaderElement[]> contentHeaders, final Object ctx) throws Exception {
    final JenkinsClient client = (JenkinsClient) ctx;
    final HttpRequestBase get = getNewHttpRequest(null, linkUrl);
    if (userAgent != null) {
        get.setHeader("User-Agent", userAgent);
    }//from  w w w.ja  va 2  s.  c  o  m
    final HttpResponse response = client.http.execute(get);
    try {
        final int status = response.getStatusLine().getStatusCode();
        if (status != HttpURLConnection.HTTP_OK) {
            throw new IOException("HTTP- " + get.getMethod() + " " + linkUrl + " returned status " + status);
        }

        if (contentHeaders != null) {
            for (final Header header : response.getAllHeaders()) {
                contentHeaders.put(header.getName(), header.getElements());
            }
        }

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final InputStream content = response.getEntity().getContent();
        IOUtils.copy(content, out);
        content.close();
        return out.toByteArray();
    } finally {
        get.releaseConnection();
    }
}

From source file:org.lol.reddit.cache.CacheDownload.java

private void performDownload(final HttpClient httpClient, final HttpRequestBase httpRequest) {

    if (mInitiator.isJson)
        httpRequest.setHeader("Accept-Encoding", "gzip");

    final HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, mInitiator.getCookies());

    final HttpResponse response;
    final StatusLine status;

    try {//  w w  w .j  a  v  a  2s  .  co m
        if (mCancelled) {
            mInitiator.notifyFailure(RequestFailureType.CANCELLED, null, null, "Cancelled");
            return;
        }
        response = httpClient.execute(httpRequest, localContext);
        status = response.getStatusLine();

    } catch (Throwable t) {

        if (t.getCause() != null && t.getCause() instanceof RedirectException
                && httpRequest.getURI().getHost().endsWith("reddit.com")) {

            mInitiator.notifyFailure(RequestFailureType.REDDIT_REDIRECT, t, null,
                    "Unable to open a connection");
        } else {
            mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, null, "Unable to open a connection");
        }
        return;
    }

    if (status.getStatusCode() != 200) {
        mInitiator.notifyFailure(RequestFailureType.REQUEST, null, status,
                String.format("HTTP error %d (%s)", status.getStatusCode(), status.getReasonPhrase()));
        return;
    }

    if (mCancelled) {
        mInitiator.notifyFailure(RequestFailureType.CANCELLED, null, null, "Cancelled");
        return;
    }

    final HttpEntity entity = response.getEntity();

    if (entity == null) {
        mInitiator.notifyFailure(RequestFailureType.CONNECTION, null, status,
                "Did not receive a valid HTTP response");
        return;
    }

    final InputStream is;

    final String mimetype;
    try {
        is = entity.getContent();
        mimetype = entity.getContentType() == null ? null : entity.getContentType().getValue();
    } catch (Throwable t) {
        t.printStackTrace();
        mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, status, "Could not open an input stream");
        return;
    }

    final NotifyOutputStream cacheOs;
    final CacheManager.WritableCacheFile cacheFile;
    if (mInitiator.cache) {
        try {
            cacheFile = manager.openNewCacheFile(mInitiator, session, mimetype);
            cacheOs = cacheFile.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Could not access the local cache");
            return;
        }
    } else {
        cacheOs = null;
        cacheFile = null;
    }

    final long contentLength = entity.getContentLength();

    if (mInitiator.isJson) {

        final InputStream bis;

        if (mInitiator.cache) {

            bis = new BufferedInputStream(
                    new CachingInputStream(is, cacheOs, new CachingInputStream.BytesReadListener() {
                        public void onBytesRead(final long total) {
                            mInitiator.notifyProgress(total, contentLength);
                        }
                    }), 8 * 1024);

        } else {
            bis = new BufferedInputStream(is, 8 * 1024);
        }

        final JsonValue value;

        try {
            value = new JsonValue(bis);

            synchronized (this) {
                mInitiator.notifyJsonParseStarted(value, RRTime.utcCurrentTimeMillis(), session, false);
            }

            value.buildInThisThread();

        } catch (Throwable t) {
            t.printStackTrace();
            mInitiator.notifyFailure(RequestFailureType.PARSE, t, null, "Error parsing the JSON stream");
            return;
        }

        if (mInitiator.cache && cacheFile != null) {
            try {
                mInitiator.notifySuccess(cacheFile.getReadableCacheFile(), RRTime.utcCurrentTimeMillis(),
                        session, false, mimetype);
            } catch (IOException e) {
                if (e.getMessage().contains("ENOSPC")) {
                    mInitiator.notifyFailure(RequestFailureType.DISK_SPACE, e, null, "Out of disk space");
                } else {
                    mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Cache file not found");
                }
            }
        }

    } else {

        if (!mInitiator.cache) {
            BugReportActivity.handleGlobalError(mInitiator.context, "Cache disabled for non-JSON request");
            return;
        }

        try {
            final byte[] buf = new byte[8 * 1024];

            int bytesRead;
            long totalBytesRead = 0;
            while ((bytesRead = is.read(buf)) > 0) {
                totalBytesRead += bytesRead;
                cacheOs.write(buf, 0, bytesRead);
                mInitiator.notifyProgress(totalBytesRead, contentLength);
            }

            cacheOs.flush();
            cacheOs.close();

            try {
                mInitiator.notifySuccess(cacheFile.getReadableCacheFile(), RRTime.utcCurrentTimeMillis(),
                        session, false, mimetype);
            } catch (IOException e) {
                if (e.getMessage().contains("ENOSPC")) {
                    mInitiator.notifyFailure(RequestFailureType.DISK_SPACE, e, null, "Out of disk space");
                } else {
                    mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Cache file not found");
                }
            }

        } catch (IOException e) {

            if (e.getMessage() != null && e.getMessage().contains("ENOSPC")) {
                mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Out of disk space");

            } else {
                e.printStackTrace();
                mInitiator.notifyFailure(RequestFailureType.CONNECTION, e, null,
                        "The connection was interrupted");
            }

        } catch (Throwable t) {
            t.printStackTrace();
            mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, null, "The connection was interrupted");
        }
    }
}

From source file:com.ontotext.s4.gdbaas.createRepo.service.GdbaasClient.java

/**
 * Serialize a ProcessingRequest and send it to Self Service Semantic Suite
 * Online Processing Service/*from   w  w  w  .  j av a 2s.com*/
 * 
 * @param pr
 *            the processing request to send
 * @param acceptType
 *            the type of output we want to produce
 * @throws URISyntaxException
 */
private String processRequest(String message, String acceptType, String contentType, HttpRequestBase request,
        String contentTypeHeader, String acceptTypeHeader) throws URISyntaxException {

    request.setHeader("Accept", acceptTypeHeader);
    request.setHeader("Content-Type", contentTypeHeader);
    request.setHeader("Accept-Encoding", "gzip");

    if (request instanceof HttpEntityEnclosingRequestBase) {
        System.out.println("POST body is:");
        System.out.println(message);
        ((HttpEntityEnclosingRequestBase) request)
                .setEntity(new StringEntity(message, Charset.forName("UTF-8")));
    }

    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(request, ctx);
        StatusLine sl = response.getStatusLine();
        int statusCode = sl.getStatusCode();
        switch (statusCode) {
        case 200: {
            // Request was processed successfully
            System.out.println("SUCCESS");
            System.out.println(response.toString());
            return getContent(response);
        }
        case 204: {
            // Request was processed successfully
            System.out.println("SUCCESS");
            return response.toString();
        }
        case 400: {
            // Bad request, there is some problem with user input
            System.out.println("Bad request");
            System.out.println(response.toString());
            System.out.println(getContent(response));
            break;
        }
        case 403: {
            // Problem with user authentication
            System.out.println("Error during authentication");
            System.out.println(response.toString());
            System.out.println(getContent(response));
            break;
        }
        case 404: {
            // Not found
            System.out.println("Not found, check endpoint URL");
            System.out.println(response.toString());
            System.out.println(getContent(response));
            break;
        }
        case 406: {
            // Not Accepted
            System.out.println("The request was not accepted. Check Accept header");
            System.out.println(response.toString());
            System.out.println(getContent(response));
            break;
        }
        case 408: {
            // Processing this request took too long
            System.out.println("Could not process document in time");
            System.out.println(response.toString());
            System.out.println(getContent(response));
            break;
        }
        case 415: {
            // Unsupported media type
            System.out.println("Invalid value in Content-Type header");
            System.out.println(response.toString());
            System.out.println(getContent(response));
            break;
        }
        case 500: {
            // Internal server error
            System.out.println("Error during processing");
            System.out.println(response.toString());
            System.out.println(getContent(response));
            break;
        }
        default: {
            System.out.println("Could not process request");
            System.out.println(response.toString());
            System.out.println(getContent(response));
            break;
        }
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            response.close();
        } catch (IOException e) {
        }
    }
    return null;
}

From source file:de.fiz.oauthclient.servlet.OauthServlet.java

private void setAuthHeader(HttpServletRequest request, HttpRequestBase method) {
    if ("token".equals(request.getParameter("authtype"))) {
        String token = (String) request.getSession().getAttribute(accessTokenAttributeName);
        if (token != null && !token.isEmpty()) {
            String authorization = "Bearer " + token;
            method.setHeader("Authorization", authorization);
        }/*from   w  ww .  ja  v a 2 s .  c o m*/
    } else {
        String authorization;
        if (request.getParameter("authstring") != null) {
            authorization = request.getParameter("authstring");
        } else {
            authorization = this.authorization;
        }
        byte[] encodedBytes = Base64.encodeBase64(authorization.getBytes());
        authorization = "Basic " + new String(encodedBytes);
        method.setHeader("Authorization", authorization);
    }
}

From source file:com.logicoy.pdmp.pmpi.http.SimpleWebClient.java

public PMPIHttpClientResponse sendRequest(SessionObject SessionObj, SimpleWebClientSettings settings) {

    HttpRequestBase httpRequest = null;
    //HttpPost httpPost = null;
    //HttpGet httpGet = null;
    try {/*  w  w w  . j ava2 s  .c om*/

        if (settings.getAction() == SimpleWebClientSettings.ActionType.POST) {
            httpRequest = new HttpPost(settings.getUri());
        } else {
            httpRequest = new HttpGet(settings.getUri());
        }

        httpRequest.setHeader("Content-Type", settings.getContentType());
        httpRequest.setHeader("Allow-Auto-Redirect", String.valueOf(settings.getAutoRedirect()));
        httpRequest.setHeader("Keep-Alive", String.valueOf(settings.getKeepAlive()));

        if (settings.getAccept() != null && !settings.getAccept().equals("")) {
            httpRequest.setHeader("Accept", settings.getAccept());
        }
        if (settings.getMessageBody() != null && !settings.getMessageBody().equals("")
                && settings.getAction() == SimpleWebClientSettings.ActionType.POST) {
            byte[] postData = settings.getMessageBody().getBytes(Charset.forName("UTF-8"));

            StringEntity entity = new StringEntity(settings.getMessageBody(),
                    ContentType.create(settings.getContentType(), Charset.forName("UTF-8")));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            entity.writeTo(baos);
            HttpPost httpPost = (HttpPost) httpRequest;
            httpPost.setEntity(entity);

        }
        try {

            httpclient.setCookieStore(SessionObj.getCookieStore());
            httpResponse = httpclient.execute(httpRequest);
        } catch (IOException ioe) {
            logger.log(Level.SEVERE, "Error while posting data", ioe);
            throw ioe;
        }
        PMPIHttpClientResponse resp = new PMPIHttpClientResponse();
        populateResponseObject(httpResponse, resp);
        System.out
                .println("Status code returned from server : " + httpResponse.getStatusLine().getStatusCode());
        System.out.println("Status resson phrase returned from server : "
                + httpResponse.getStatusLine().getReasonPhrase());
        //EntityUtils.consume(httpResponse.getEntity());
        return resp;

    } catch (Exception e) {
        ok = false;
        logger.log(Level.SEVERE, e.getMessage(), e);
        return null;
    } finally {
        if (httpRequest != null) {
            httpRequest.releaseConnection();
        }
    }

}

From source file:co.cask.cdap.gateway.tools.ClientToolBase.java

/**
 * Sends http requests with apikey and access token headers
 * and checks the status of the request afterwards.
 *
 * @param requestBase The request to send. This method adds the apikey and access token headers
 *                    if they are valid.
 * @param expectedCodes The list of expected status codes from the request. If set to null,
 *                      this method checks that the status code is OK.
 * @return The HttpResponse if the request was successfully sent and the request status code
 * is one of expectedCodes or OK if expectedCodes is null. Otherwise, returns null.
 *//*from   w  ww  .  j a  va  2  s .  c  o  m*/
protected HttpResponse sendHttpRequest(HttpClient client, HttpRequestBase requestBase,
        List<Integer> expectedCodes) {
    if (apikey != null) {
        requestBase.setHeader(Constants.Gateway.API_KEY, apikey);
    }
    if (accessToken != null) {
        requestBase.setHeader("Authorization", "Bearer " + accessToken);
    }
    try {
        HttpResponse response = client.execute(requestBase);
        // if expectedCodes is null, just check that we have OK status code
        if (expectedCodes == null) {
            if (!checkHttpStatus(response, HttpStatus.SC_OK)) {
                return null;
            }
        } else {
            if (!checkHttpStatus(response, expectedCodes)) {
                return null;
            }
        }
        return response;
    } catch (IOException e) {
        System.err.println("Error sending HTTP request: " + e.getMessage());
        return null;
    }
}

From source file:de.cosmocode.issuetracker.activecollab.DefaultActiveCollab.java

private JsonNode request(HttpRequestBase request, String pathInfo) throws IOException {
    final URI requestUri;
    try {/*from   w  w  w .  j  a  va  2s . c o  m*/
        requestUri = new URI(apiUri.toString() + "?token=" + token + "&path_info=" + pathInfo);
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
    request.setURI(requestUri);

    request.setHeader("Accept", "application/json");

    final ResponseHandler<String> responseHandler = new BasicResponseHandler();
    final String response = httpclient.execute(request, responseHandler);

    return mapper.readValue(response, JsonNode.class);
}