Example usage for org.apache.http.client.methods HttpUriRequest addHeader

List of usage examples for org.apache.http.client.methods HttpUriRequest addHeader

Introduction

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

Prototype

void addHeader(Header header);

Source Link

Usage

From source file:com.android.aft.AFNetworkConnection.AFNetworkConnection.java

private HttpUriRequest buildUriRequest(AFNetworkConnectionRequest request)
        throws UnsupportedEncodingException, URISyntaxException {
    // Create uri
    HttpUriRequest uri_request = null;

    switch (request.method) {

    case Post:/*www. java2s  .  c o m*/
        final URI uriPost = new URI(request.url);
        uri_request = new HttpPost(uriPost);

        // Add the parameters to the POST request if any
        if (request.parameters != null && !request.parameters.isEmpty()) {

            final List<NameValuePair> postRequestParameters = new ArrayList<NameValuePair>();
            final ArrayList<String> keyList = new ArrayList<String>(request.parameters.keySet());
            final int keyListLength = keyList.size();

            for (int i = 0; i < keyListLength; i++) {
                final String key = keyList.get(i);
                postRequestParameters.add(new BasicNameValuePair(key, request.parameters.get(key)));
            }

            if (AFConfig.INFO_LOGS_ENABLED) {
                Log.i(LOG_TAG, "retrieveStringFromService - POST Request - parameters list (key => value) : ");

                final int postRequestParametersLength = postRequestParameters.size();
                for (int i = 0; i < postRequestParametersLength; i++) {
                    final NameValuePair nameValuePair = postRequestParameters.get(i);
                    Log.i(LOG_TAG, "- " + nameValuePair.getName() + " => " + nameValuePair.getValue());
                }
            }

            // uri_request.setHeader(HTTP.CONTENT_TYPE,
            // "application/x-www-form-urlencoded");
            ((HttpPost) uri_request).setEntity(new UrlEncodedFormEntity(postRequestParameters, "UTF-8"));
        }
        if (null != request.postText) {
            ((HttpPost) uri_request).setEntity(new StringEntity(request.postText));
        }
        if (null != request.entity) {
            ((HttpPost) uri_request).setEntity(request.entity);
        }
        break;
    case Delete:
        final URI uriDelete = new URI(request.url);
        uri_request = new HttpDelete(uriDelete);

        // Add the parameters to the DELETE request if any
        if (request.parameters != null && !request.parameters.isEmpty()) {

            final List<NameValuePair> deleteRequestParameters = new ArrayList<NameValuePair>();
            final ArrayList<String> keyList = new ArrayList<String>(request.parameters.keySet());
            final int keyListLength = keyList.size();

            for (int i = 0; i < keyListLength; i++) {
                final String key = keyList.get(i);
                deleteRequestParameters.add(new BasicNameValuePair(key, request.parameters.get(key)));
            }

            if (AFConfig.INFO_LOGS_ENABLED) {
                Log.i(LOG_TAG,
                        "retrieveStringFromService - DELETE Request - parameters list (key => value) : ");

                final int deleteRequestParametersLength = deleteRequestParameters.size();
                for (int i = 0; i < deleteRequestParametersLength; i++) {
                    final NameValuePair nameValuePair = deleteRequestParameters.get(i);
                    Log.i(LOG_TAG, "- " + nameValuePair.getName() + " => " + nameValuePair.getValue());
                }
            }

        }
        break;
    case Put:
        final URI uriPut = new URI(request.url);
        uri_request = new HttpPut(uriPut);

        // Add the parameters to the PUT request if any
        if (request.parameters != null && !request.parameters.isEmpty()) {

            final List<NameValuePair> putRequestParameters = new ArrayList<NameValuePair>();
            final ArrayList<String> keyList = new ArrayList<String>(request.parameters.keySet());
            final int keyListLength = keyList.size();

            for (int i = 0; i < keyListLength; i++) {
                final String key = keyList.get(i);
                putRequestParameters.add(new BasicNameValuePair(key, request.parameters.get(key)));
            }

            if (AFConfig.INFO_LOGS_ENABLED) {
                Log.i(LOG_TAG, "retrieveStringFromService - PUT Request - parameters list (key => value) : ");

                final int putRequestParametersLength = putRequestParameters.size();
                for (int i = 0; i < putRequestParametersLength; i++) {
                    final NameValuePair nameValuePair = putRequestParameters.get(i);
                    Log.i(LOG_TAG, "- " + nameValuePair.getName() + " => " + nameValuePair.getValue());
                }
            }
            if (null != request.postText) {
                ((HttpPut) uri_request).setEntity(new StringEntity(request.postText));
            }

        }
        break;
    case Get:
    default:
        final StringBuffer sb = new StringBuffer();
        sb.append(request.url);
        // Add the parameters to the GET url if any
        if (request.parameters != null && !request.parameters.isEmpty()) {
            sb.append("?");

            final ArrayList<String> keyList = new ArrayList<String>(request.parameters.keySet());
            final int keyListLength = keyList.size();

            for (int i = 0; i < keyListLength; i++) {
                final String key = keyList.get(i);
                sb.append(URLEncoder.encode(key, "UTF-8"));
                sb.append("=");
                sb.append(request.parameters.get(key));
                if (i < keyListLength - 1) {
                    sb.append("&");
                }
            }
        }

        if (AFConfig.INFO_LOGS_ENABLED) {
            Log.i(LOG_TAG, "retrieveStringFromService - GET Request - complete URL with parameters if any : "
                    + sb.toString());
        }

        final URI uri = new URI(sb.toString());
        uri_request = new HttpGet(uri);
    }
    // Add post text (send xml)

    // Add the request headers if any
    if (request.headers != null && !request.headers.isEmpty()) {

        final int headersLength = request.headers.size();

        for (int i = 0; i < headersLength; i++) {
            uri_request.addHeader(request.headers.get(i));
        }
    }
    return uri_request;
}

From source file:org.codelibs.robot.client.http.HcHttpClient.java

protected ResponseData processHttpMethod(final String url, final HttpUriRequest httpRequest) {
    try {//from   w ww .  ja v a  2s.co  m
        processRobotsTxt(url);
    } catch (final RobotCrawlAccessException e) {
        if (logger.isInfoEnabled()) {
            final StringBuilder buf = new StringBuilder();
            buf.append(e.getMessage());
            if (e.getCause() != null) {
                buf.append(e.getCause().getMessage());
            }
            logger.info(buf.toString());
        } else if (logger.isDebugEnabled()) {
            logger.debug("Crawling Access Exception at " + url, e);
        }
    }

    // request header
    for (final Header header : requestHeaderList) {
        httpRequest.addHeader(header);
    }

    ResponseData responseData = null;
    InputStream inputStream = null;
    HttpEntity httpEntity = null;
    try {
        // get a content
        final HttpResponse response = executeHttpClient(httpRequest);
        httpEntity = response.getEntity();

        final int httpStatusCode = response.getStatusLine().getStatusCode();
        // redirect
        if (isRedirectHttpStatus(httpStatusCode)) {
            final Header locationHeader = response.getFirstHeader("location");
            if (locationHeader == null) {
                logger.warn("Invalid redirect location at " + url);
            } else {
                responseData = new ResponseData();
                responseData.setRedirectLocation(locationHeader.getValue());
                return responseData;
            }
        }

        long contentLength = 0;
        String contentEncoding = Constants.UTF_8;
        if (httpEntity == null) {
            inputStream = new ByteArrayInputStream(new byte[0]);
        } else {
            final InputStream responseBodyStream = httpEntity.getContent();
            final File outputFile = File.createTempFile("s2robot-HcHttpClient-", ".out");
            DeferredFileOutputStream dfos = null;
            try {
                try {
                    dfos = new DeferredFileOutputStream(responseBodyInMemoryThresholdSize, outputFile);
                    CopyUtil.copy(responseBodyStream, dfos);
                    dfos.flush();
                } finally {
                    IOUtils.closeQuietly(dfos);
                }
            } catch (final Exception e) {
                if (!outputFile.delete()) {
                    logger.warn("Could not delete " + outputFile.getAbsolutePath());
                }
                throw e;
            }

            if (dfos.isInMemory()) {
                inputStream = new ByteArrayInputStream(dfos.getData());
                contentLength = dfos.getData().length;
                if (!outputFile.delete()) {
                    logger.warn("Could not delete " + outputFile.getAbsolutePath());
                }
            } else {
                inputStream = new TemporaryFileInputStream(outputFile);
                contentLength = outputFile.length();
            }

            final Header contentEncodingHeader = httpEntity.getContentEncoding();
            if (contentEncodingHeader != null) {
                contentEncoding = contentEncodingHeader.getValue();
            }
        }

        String contentType = null;
        final Header contentTypeHeader = response.getFirstHeader("Content-Type");
        if (contentTypeHeader != null) {
            contentType = contentTypeHeader.getValue();
            final int idx = contentType.indexOf(';');
            if (idx > 0) {
                contentType = contentType.substring(0, idx);
            }
        }

        // check file size
        if (contentLengthHelper != null) {
            final long maxLength = contentLengthHelper.getMaxLength(contentType);
            if (contentLength > maxLength) {
                throw new MaxLengthExceededException("The content length (" + contentLength + " byte) is over "
                        + maxLength + " byte. The url is " + url);
            }
        }

        responseData = new ResponseData();
        responseData.setUrl(url);
        responseData.setCharSet(contentEncoding);
        if (httpRequest instanceof HttpHead) {
            responseData.setMethod(Constants.HEAD_METHOD);
        } else {
            responseData.setMethod(Constants.GET_METHOD);
        }
        responseData.setResponseBody(inputStream);
        responseData.setHttpStatusCode(httpStatusCode);
        for (final Header header : response.getAllHeaders()) {
            responseData.addMetaData(header.getName(), header.getValue());
        }
        if (contentType == null) {
            responseData.setMimeType(defaultMimeType);
        } else {
            responseData.setMimeType(contentType);
        }
        final Header contentLengthHeader = response.getFirstHeader("Content-Length");
        if (contentLengthHeader == null) {
            responseData.setContentLength(contentLength);
        } else {
            final String value = contentLengthHeader.getValue();
            try {
                responseData.setContentLength(Long.parseLong(value));
            } catch (final Exception e) {
                responseData.setContentLength(contentLength);
            }
        }
        final Header lastModifiedHeader = response.getFirstHeader("Last-Modified");
        if (lastModifiedHeader != null) {
            final String value = lastModifiedHeader.getValue();
            if (StringUtil.isNotBlank(value)) {
                final Date d = parseLastModified(value);
                if (d != null) {
                    responseData.setLastModified(d);
                }
            }
        }

        return responseData;
    } catch (final UnknownHostException e) {
        httpRequest.abort();
        IOUtils.closeQuietly(inputStream);
        throw new RobotCrawlAccessException("Unknown host(" + e.getMessage() + "): " + url, e);
    } catch (final NoRouteToHostException e) {
        httpRequest.abort();
        IOUtils.closeQuietly(inputStream);
        throw new RobotCrawlAccessException("No route to host(" + e.getMessage() + "): " + url, e);
    } catch (final ConnectException e) {
        httpRequest.abort();
        IOUtils.closeQuietly(inputStream);
        throw new RobotCrawlAccessException("Connection time out(" + e.getMessage() + "): " + url, e);
    } catch (final SocketException e) {
        httpRequest.abort();
        IOUtils.closeQuietly(inputStream);
        throw new RobotCrawlAccessException("Socket exception(" + e.getMessage() + "): " + url, e);
    } catch (final IOException e) {
        httpRequest.abort();
        IOUtils.closeQuietly(inputStream);
        throw new RobotCrawlAccessException("I/O exception(" + e.getMessage() + "): " + url, e);
    } catch (final RobotSystemException e) {
        httpRequest.abort();
        IOUtils.closeQuietly(inputStream);
        throw e;
    } catch (final Exception e) {
        httpRequest.abort();
        IOUtils.closeQuietly(inputStream);
        throw new RobotSystemException("Failed to access " + url, e);
    } finally {
        EntityUtils.consumeQuietly(httpEntity);
    }
}

From source file:org.flowable.app.rest.service.BaseSpringRestTestCase.java

protected CloseableHttpResponse internalExecuteRequest(HttpUriRequest request, int expectedStatusCode,
        boolean addJsonContentType) {
    CloseableHttpResponse response = null;
    try {//from   ww  w  .  j a va 2s .c om
        if (addJsonContentType && request.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
            // Revert to default content-type
            request.addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
        }
        response = client.execute(request);
        Assert.assertNotNull(response.getStatusLine());

        int responseStatusCode = response.getStatusLine().getStatusCode();
        if (expectedStatusCode != responseStatusCode) {
            LOGGER.info("Wrong status code : {}, but should be {}", responseStatusCode, expectedStatusCode);
            if (response.getEntity() != null) {
                LOGGER.info("Response body: {}", IOUtils.toString(response.getEntity().getContent(), "utf-8"));
            }
        }

        Assert.assertEquals(expectedStatusCode, responseStatusCode);
        httpResponses.add(response);
        return response;

    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.flowable.cmmn.rest.service.BaseSpringRestTestCase.java

protected CloseableHttpResponse internalExecuteRequest(HttpUriRequest request, int expectedStatusCode,
        boolean addJsonContentType) {
    try {//w  w  w  . j a  v  a  2 s.c o  m
        if (addJsonContentType && request.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
            // Revert to default content-type
            request.addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
        }
        CloseableHttpResponse response = client.execute(request);
        Assert.assertNotNull(response.getStatusLine());

        int responseStatusCode = response.getStatusLine().getStatusCode();
        if (expectedStatusCode != responseStatusCode) {
            LOGGER.info("Wrong status code : {}, but should be {}", responseStatusCode, expectedStatusCode);
            if (response.getEntity() != null) {
                LOGGER.info("Response body: {}", IOUtils.toString(response.getEntity().getContent(), "utf-8"));
            }
        }

        Assert.assertEquals(expectedStatusCode, responseStatusCode);
        httpResponses.add(response);
        return response;

    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.flowable.content.rest.service.api.BaseSpringContentRestTestCase.java

protected CloseableHttpResponse internalExecuteRequest(HttpUriRequest request, int expectedStatusCode,
        boolean addJsonContentType) {
    CloseableHttpResponse response = null;
    try {//from   www .  j av a2 s  . c o m
        if (addJsonContentType && request.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
            // Revert to default content-type
            request.addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
        }
        response = client.execute(request);
        Assert.assertNotNull(response.getStatusLine());

        int responseStatusCode = response.getStatusLine().getStatusCode();
        if (expectedStatusCode != responseStatusCode) {
            LOGGER.info("Wrong status code : {}, but should be {}", responseStatusCode, expectedStatusCode);
            LOGGER.info("Response body: {}", IOUtils.toString(response.getEntity().getContent()));
        }

        Assert.assertEquals(expectedStatusCode, responseStatusCode);
        httpResponses.add(response);
        return response;

    } catch (ClientProtocolException e) {
        Assert.fail(e.getMessage());
    } catch (IOException e) {
        Assert.fail(e.getMessage());
    }
    return null;
}

From source file:org.wso2.am.integration.tests.other.APIMANAGER4464BackendReturningStatusCode204TestCase.java

@Test(groups = "wso2.am", description = "Send a request to a backend returning 204 and check if the expected result is received")
public void testAPIReturningStatusCode204() {
    //Login to the API Publisher
    try {/*w ww  . j a v a 2 s . c om*/
        apiPublisher.login(publisherContext.getContextTenant().getContextUser().getUserName(),
                publisherContext.getContextTenant().getContextUser().getPassword());
    } catch (APIManagerIntegrationTestException e) {
        log.error("APIManagerIntegrationTestException " + e.getMessage());
        Assert.assertTrue(false);
    } catch (XPathExpressionException e) {
        log.error("XPathExpressionException " + e.getMessage());
        Assert.assertTrue(false);
    }

    String apiName = "Test_API" + userMode;
    String apiVersion = "1.0.0";
    String apiContext = "/somecontext" + userMode;
    String endpointUrl = gatewayUrlsMgt.getWebAppURLNhttp() + "response";

    //Create the api creation request object
    APIRequest apiRequest = null;
    try {
        apiRequest = new APIRequest(apiName, apiContext, new URL(endpointUrl));
    } catch (APIManagerIntegrationTestException e) {
        log.error("Error creating APIRequest " + e.getMessage());
        Assert.assertTrue(false);
    } catch (MalformedURLException e) {
        log.error("Invalid URL " + gatewayUrlsMgt.getWebAppURLNhttp() + "response", e);
        Assert.assertTrue(false);
    }

    apiRequest.setVersion(apiVersion);
    apiRequest.setTiersCollection("Unlimited");
    apiRequest.setTier("Unlimited");
    apiRequest.setResourceMethod("POST");

    try {
        apiRequest.setProvider(publisherContext.getContextTenant().getContextUser().getUserName());

        //Add the API using the API publisher.
        apiPublisher.addAPI(apiRequest);

        APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(apiName,
                publisherContext.getContextTenant().getContextUser().getUserName(),
                APILifeCycleState.PUBLISHED);
        //Publish the API
        apiPublisher.changeAPILifeCycleStatus(updateRequest);

        //Login to the API Store
        apiStore.login(storeContext.getContextTenant().getContextUser().getUserName(),
                storeContext.getContextTenant().getContextUser().getPassword());

        //Add an Application in the Store.
        apiStore.addApplication("APP", "Unlimited", "", "");

        //Subscribe the API to the DefaultApplication
        SubscriptionRequest subscriptionRequest = new SubscriptionRequest(apiName, apiVersion,
                storeContext.getContextTenant().getContextUser().getUserName(), "APP", "Unlimited");
        apiStore.subscribe(subscriptionRequest);

        //Generate production token and invoke with that
        APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator("APP");
        String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData();
        JSONObject response = new JSONObject(responseString);

        //Get the accessToken which was generated.
        String accessToken = response.getJSONObject("data").getJSONObject("key").getString("accessToken");

        String apiInvocationUrl;
        if (userMode == TestUserMode.TENANT_ADMIN || userMode == TestUserMode.TENANT_USER) {
            apiInvocationUrl = gatewayUrlsMgt.getWebAppURLNhttp() + "/t/wso2.com" + apiContext + "/"
                    + apiVersion;
        } else {
            apiInvocationUrl = gatewayUrlsMgt.getWebAppURLNhttp() + apiContext + "/" + apiVersion;
        }

        HttpClient httpclient = new DefaultHttpClient();
        HttpUriRequest post = new HttpPost(apiInvocationUrl);
        post.addHeader(new BasicHeader("Authorization", "Bearer " + accessToken));
        org.apache.http.HttpResponse httpResponse = httpclient.execute(post);

        Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(), 204, "Status Code is not 204");

    } catch (APIManagerIntegrationTestException e) {
        log.error("APIManagerIntegrationTestException " + e.getMessage(), e);
        Assert.assertTrue(false);
    } catch (JSONException e) {
        log.error("Error parsing JSON to get access token " + e.getMessage(), e);
        Assert.assertTrue(false);
    } catch (XPathExpressionException e) {
        log.error("XPathExpressionException " + e.getMessage(), e);
        Assert.assertTrue(false);
    } catch (IOException e) {
        log.error("IOException " + e.getMessage(), e);
        Assert.assertTrue(false);
    }
}

From source file:org.wso2.am.integration.tests.other.LocationHeaderTestCase.java

@Test(groups = "wso2.am", description = "Check whether the Location header is correct")
public void testAPIWithLocationHeader() throws Exception {

    //Login to the API Publisher
    HttpResponse response;//from   ww w  .j a  v a  2  s .  c  o  m
    response = apiPublisher.login(user.getUserName(), user.getPassword());
    verifyResponse(response);

    String apiName = "LocationHeaderAPI";
    String apiVersion = "1.0.0";
    String apiContext = "locheader";
    String endpointUrl = getAPIInvocationURLHttp("response");

    //Create the api creation request object
    APIRequest apiRequest;
    apiRequest = new APIRequest(apiName, apiContext, new URL(endpointUrl));

    apiRequest.setVersion(apiVersion);
    apiRequest.setTiersCollection(APIMIntegrationConstants.API_TIER.UNLIMITED);
    apiRequest.setTier(APIMIntegrationConstants.API_TIER.UNLIMITED);

    //Add the API using the API publisher.
    response = apiPublisher.addAPI(apiRequest);
    verifyResponse(response);

    APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(apiName, user.getUserName(),
            APILifeCycleState.PUBLISHED);
    //Publish the API
    response = apiPublisher.changeAPILifeCycleStatus(updateRequest);
    verifyResponse(response);

    //Login to the API Store
    response = apiStore.login(user.getUserName(), user.getPassword());
    verifyResponse(response);

    //Add an Application in the Store.
    response = apiStore.addApplication("LocHeaderAPP", APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, "",
            "");
    verifyResponse(response);

    //Subscribe the API to the DefaultApplication
    SubscriptionRequest subscriptionRequest = new SubscriptionRequest(apiName, apiVersion, user.getUserName(),
            "LocHeaderAPP", APIMIntegrationConstants.API_TIER.UNLIMITED);
    response = apiStore.subscribe(subscriptionRequest);
    verifyResponse(response);

    //Generate production token and invoke with that
    APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator("LocHeaderAPP");
    String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData();
    JSONObject responseJson = new JSONObject(responseString);

    //Get the accessToken which was generated.
    String accessToken = responseJson.getJSONObject("data").getJSONObject("key").getString("accessToken");

    //Going to access the API with the version in the request url.
    String apiInvocationUrl = getAPIInvocationURLHttp(apiContext, apiVersion);

    HttpClient httpclient = new DefaultHttpClient();
    HttpUriRequest get = new HttpGet(apiInvocationUrl);
    get.addHeader(new BasicHeader("Authorization", "Bearer " + accessToken));

    waitForAPIDeploymentSync(apiRequest.getProvider(), apiRequest.getName(), apiRequest.getVersion(),
            APIMIntegrationConstants.IS_API_EXISTS);

    org.apache.http.HttpResponse httpResponse = httpclient.execute(get);
    Header locationHeader = httpResponse.getFirstHeader("Location");

    Assert.assertFalse(locationHeader.getValue().endsWith("//abc/domain"),
            "Location header contains additional / character");
    Assert.assertTrue(locationHeader.getValue().endsWith("/abc/domain"),
            "Unexpected Location header. Expected to end with " + "/abc/domain but received " + locationHeader);

}