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:org.wso2.am.integration.tests.other.APIMANAGER5326CustomStatusMsgTestCase.java

@Test(groups = "wso2.am", description = "testing error responses")
public void testAPIErrorResponse() throws Exception {

    //Login to the API Publisher
    org.wso2.carbon.automation.test.utils.http.client.HttpResponse response;
    response = apiPublisher.login(user.getUserName(), user.getPassword());
    verifyResponse(response);//from  w w  w. jav  a  2 s .c om

    String apiName = "ErrorResponseCheckAPI";
    String apiVersion = "1.0.0";
    String apiContext = "message";
    String endpointUrl = "http://" + InetAddress.getLocalHost().getHostName() + ":1989";
    String appName = "testApplication";

    try {
        //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(appName, APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, "",
                "");
        verifyResponse(response);

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

        //Generate production token and invoke with that
        APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator(appName);
        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 getRequest1 = new HttpGet(apiInvocationUrl);
        getRequest1.addHeader(new BasicHeader("Authorization", "Bearer " + accessToken));

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

        org.apache.http.HttpResponse httpResponse = httpclient.execute(getRequest1);
        Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(), 400, "Response Code Mismatched");
        Assert.assertEquals(httpResponse.getStatusLine().toString().contains("Custom response"), true,
                "Response received with Custom Status Message");

    } 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:com.microsoft.live.ApiRequest.java

/**
 * Performs the Http Request and returns the response from the server
 *
 * @return an instance of ResponseType from the server
 * @throws LiveOperationException if there was an error executing the HttpRequest
 *//*from   w  w w  .java  2 s  .  c  om*/
public ResponseType execute() throws LiveOperationException {
    // Let subclass decide which type of request to instantiate
    HttpUriRequest request = this.createHttpRequest();

    request.addHeader(LIVE_LIBRARY_HEADER);

    if (this.session.willExpireInSecs(SESSION_REFRESH_BUFFER_SECS)) {
        this.session.refresh();
    }

    // if the session will soon expire, try to send the request without a token.
    // the request *may* not need the token, let's give it a try rather than
    // risk a request with an invalid token.
    if (!this.session.willExpireInSecs(SESSION_TOKEN_SEND_BUFFER_SECS)) {
        request.addHeader(createAuthroizationHeader(this.session));
    }

    try {
        HttpResponse response = this.client.execute(request);

        for (Observer observer : this.observers) {
            observer.onComplete(response);
        }

        return this.responseHandler.handleResponse(response);
    } catch (ClientProtocolException e) {
        throw new LiveOperationException(ErrorMessages.SERVER_ERROR, e);
    } catch (IOException e) {
        // The IOException could contain a JSON object body
        // (see InputStreamResponseHandler.java). If it does,
        // we want to throw an exception with its message. If it does not, we want to wrap
        // the IOException.
        try {
            new JSONObject(e.getMessage());
            throw new LiveOperationException(e.getMessage());
        } catch (JSONException jsonException) {
            throw new LiveOperationException(ErrorMessages.SERVER_ERROR, e);
        }
    }
}

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

@Test(groups = "wso2.am", description = "Send a request to a backend returning 200 and check if the expected result is received")
public void testAPIReturningStatusCode200() {
    //Login to the API Publisher
    try {/*from  w ww  .j  av a  2 s .c  o m*/
        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 = "Test200_API" + userMode;
    String apiVersion = "1.0.0";
    String apiContext = "test200_api" + userMode;
    String endpointUrl = gatewayUrlsWrk.getWebAppURLNhttp() + "response200";

    //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 " + gatewayUrlsWrk.getWebAppURLNhttp() + "response200", e);
        Assert.assertTrue(false);
    }

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

    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("APP200", "Unlimited", "", "");

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

        //Generate production token and invoke with that
        APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator("APP200");
        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 = gatewayUrlsWrk.getWebAppURLNhttps() + "t/wso2.com/" + apiContext + "/"
                    + apiVersion;
        } else {
            apiInvocationUrl = gatewayUrlsWrk.getWebAppURLNhttps() + apiContext + "/" + apiVersion;
        }

        HttpClient httpclient = new DefaultHttpClient();
        HttpUriRequest get = new HttpGet(apiInvocationUrl);
        get.addHeader(new BasicHeader("Authorization", "Bearer " + accessToken));
        get.addHeader(new BasicHeader("Accept", "application/json"));
        org.apache.http.HttpResponse httpResponse = httpclient.execute(get);

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

    } 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.ErrorResponseCheckTestCase.java

@Test(groups = "wso2.am", description = "testing error responses")
public void testAPIErrorResponse() throws Exception {

    //Login to the API Publisher
    org.wso2.carbon.automation.test.utils.http.client.HttpResponse response;
    response = apiPublisher.login(user.getUserName(), user.getPassword());
    verifyResponse(response);/*from w  ww .  ja va 2  s.  c  om*/

    String apiName = "ErrorResponseSecAPI";
    String apiVersion = "1.0.0";
    String apiContext = "sec";
    String endpointUrl = getAPIInvocationURLHttp("response");

    try {
        //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("SecApp", APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, "",
                "");
        verifyResponse(response);

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

        //Generate production token and invoke with that
        APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator("SecApp");
        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 getRequest1 = new HttpGet(apiInvocationUrl);
        getRequest1.addHeader(new BasicHeader("Authorization", "Bearer " + accessToken));

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

        org.apache.http.HttpResponse httpResponse = httpclient.execute(getRequest1);
        Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(), 201, "Response Code Mismatched");

        /* -----------------test 1 : invoke with invalid resource path wit invalid context --------------- */
        String invalidApiInvocationUrl = getAPIInvocationURLHttp("invalidContext", apiVersion);

        HttpUriRequest getRequest2 = new HttpGet(invalidApiInvocationUrl);
        getRequest2.addHeader(new BasicHeader("Authorization", "Bearer " + accessToken));

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

        //releasing the connection
        if (httpResponse.getEntity() != null) {
            httpResponse.getEntity().consumeContent();
        }

        org.apache.http.HttpResponse httpResponse2 = httpclient.execute(getRequest2);
        Assert.assertEquals(httpResponse2.getStatusLine().getStatusCode(), 404, "Response Code Mismatched");
        Assert.assertEquals(httpResponse2.toString().contains("invalidContext/1.0.0"), false,
                "The message contains the resource path requested.");

        /* ----------------------------test 2 : invoke with invalid access token ---------------------------- */

        HttpUriRequest getRequest3 = new HttpGet(apiInvocationUrl);
        getRequest3.addHeader(new BasicHeader("Authorization", "Bearer " + "invalidAccessToken"));

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

        //releasing the connection
        if (httpResponse2.getEntity() != null) {
            httpResponse2.getEntity().consumeContent();
        }

        org.apache.http.HttpResponse httpResponse3 = httpclient.execute(getRequest3);
        Assert.assertEquals(httpResponse3.getStatusLine().getStatusCode(), 401, "Response Code Mismatched");
        Assert.assertEquals(httpResponse3.toString().contains("invalid_access_token"), false,
                "Access token entered is valid");

    } 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:com.citruspay.mobile.payment.client.rest.RESTClient.java

protected String openExecute(HttpUriRequest request, Collection<Header> headers)
        throws ProtocolException, RESTException {
    for (Header h : headers) {
        request.addHeader(h);
    }/* w w w  .j a  va  2  s  . c  om*/

    // execute request
    HttpResponse resp = null;
    try {
        resp = http.execute(request);

    } catch (IOException iox) {
        throw new ProtocolException(iox);
    }

    // parse response
    try {
        switch (resp.getStatusLine().getStatusCode()) {
        case HttpStatus.SC_OK:
            return EntityUtils.toString(resp.getEntity());
        case HttpStatus.SC_NO_CONTENT:
            return null;
        case HttpStatus.SC_BAD_REQUEST:
            throw new RESTException(resp.getStatusLine().getStatusCode(),
                    new JSONObject(EntityUtils.toString(resp.getEntity())));
        default:
            throw new RESTException(resp.getStatusLine().getStatusCode(),
                    new JSONObject().put("entity", EntityUtils.toString(resp.getEntity())));
        }
    } catch (JSONException jx) {
        throw new ProtocolException(jx);
    } catch (IOException iox) {
        throw new ProtocolException(iox);
    }
}

From source file:org.apache.hadoop.gateway.hive.HiveHttpClientDispatch.java

protected void addCredentialsToRequest(HttpUriRequest request) {
    if (isBasicAuthPreemptive()) {
        Principal principal = getPrimaryPrincipal();
        if (principal != null) {

            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(principal.getName(),
                    PASSWORD_PLACEHOLDER);

            request.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false));
        }//from   w w  w .  j  a  v a 2s  . com
    }
}

From source file:com.citruspay.mobile.payment.client.rest.RESTClient.java

protected JSONObject execute(HttpUriRequest request, Collection<Header> headers)
        throws ProtocolException, RESTException {
    // set headers

    try {/*from w  w  w .  j  ava 2  s  .co m*/
        if (!(headers == null)) {
            for (Header h : headers) {
                request.addHeader(h);
            }
        }
    } catch (NullPointerException e) {

    }

    // execute request
    HttpResponse resp = null;
    try {
        resp = http.execute(request);
    } catch (IOException iox) {
        throw new ProtocolException(iox);
    }

    // parse response
    try {
        switch (resp.getStatusLine().getStatusCode()) {
        case HttpStatus.SC_OK:
            return new JSONObject(EntityUtils.toString(resp.getEntity()));
        case HttpStatus.SC_NO_CONTENT:
            return new JSONObject();
        case HttpStatus.SC_BAD_REQUEST:
            throw new RESTException(resp.getStatusLine().getStatusCode(),
                    new JSONObject(EntityUtils.toString(resp.getEntity())));
        default:
            throw new RESTException(resp.getStatusLine().getStatusCode(),
                    new JSONObject().put("entity", EntityUtils.toString(resp.getEntity())));
        }
    } catch (JSONException jx) {
        throw new ProtocolException(jx);
    } catch (IOException iox) {
        throw new ProtocolException(iox);
    }
}

From source file:com.floragunn.searchguard.test.helper.rest.RestHelper.java

protected HttpResponse executeRequest(HttpUriRequest uriRequest, Header... header) throws Exception {

    CloseableHttpClient httpClient = null;
    try {// w w w. ja va2 s  . c o m

        httpClient = getHTTPClient();

        if (header != null && header.length > 0) {
            for (int i = 0; i < header.length; i++) {
                Header h = header[i];
                uriRequest.addHeader(h);
            }
        }

        HttpResponse res = new HttpResponse(httpClient.execute(uriRequest));
        log.trace(res.getBody());
        return res;
    } finally {

        if (httpClient != null) {
            httpClient.close();
        }
    }
}