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(String str, String str2);

Source Link

Usage

From source file:net.officefloor.plugin.socket.server.http.request.HttpRequestTest.java

@Override
protected void runTest() throws Throwable {

    // Start the server
    this.server.startup(this.httpServicerBuilder);
    assertEquals("Incorrect secureness for server", this.isSecure, this.server.isServerSecure());

    // Validate the configuration
    assertTrue("Must have at least 1 communication", this.configuration.communications.size() > 0);
    for (CommunicationConfig communication : this.configuration.communications) {
        assertNotNull("Communication must have a request", communication.request);
        assertNotNull("Communication must have a process", communication.process);
        assertNotNull("Communication must have a response", communication.response);
    }/* ww w.  j  av  a  2  s  .c om*/

    // Create the HTTP Client to send requests
    HttpClient client = this.server.createHttpClient();

    System.out.println("====== " + this.getName() + " ======");

    // Run the communications
    for (CommunicationConfig communication : this.configuration.communications) {

        // Indicate the request being run
        System.out.println("--- REQUEST ---");
        RequestConfig request = communication.request;
        System.out.println(request.method + " " + request.path + " " + request.version);
        for (HeaderConfig header : request.headers) {
            System.out.println(header.name + ": " + header.value);
        }
        System.out.println("\n" + request.body);

        // Specify the configuration to service the request
        RequestWork.setConfiguration(communication);

        // Create the method
        String requestUrl = this.server.getServerUrl() + request.path;
        HttpUriRequest method;
        if ("GET".equals(request.method)) {
            method = new HttpGet(requestUrl);
        } else if ("POST".equals(request.method)) {
            HttpPost post = new HttpPost(requestUrl);
            post.setEntity(new StringEntity(request.body));
            method = post;
        } else {
            TestCase.fail("Unknown request method '" + request.method + "'");
            return;
        }

        // Provide any headers to the request
        for (HeaderConfig header : request.headers) {
            method.addHeader(header.name, header.value);
        }

        // Indicate the processing
        System.out.println("--- PROCESS ---");
        ProcessConfig process = communication.process;
        System.out.println("isClose=" + process.isClose);
        System.out.println(process.body);

        // Execute the method
        HttpResponse methodResponse = client.execute(method);

        // Obtain the response body
        String actualResponseBody = HttpTestUtil.getEntityBody(methodResponse);

        // Validate no failure in processing
        this.server.validateNoTopLevelEscalation();

        // Indicate the expected response
        ResponseConfig response = communication.response;
        System.out.println("--- EXPECTED RESPONSE (isClosed=" + response.isClosed + ") ---");
        System.out.println(response.status + " " + response.version + " " + response.message);
        for (HeaderConfig header : response.headers) {
            System.out.println(header.name + ": " + header.value);
        }
        System.out.println("\n" + response.body);

        // Indicate the actual response
        System.out.println("--- ACTUAL RESPONSE ---");
        StatusLine status = methodResponse.getStatusLine();
        System.out.println(
                status.getStatusCode() + " " + status.getProtocolVersion() + " " + status.getReasonPhrase());
        for (Header header : methodResponse.getAllHeaders()) {
            System.out.println(header.getName() + ": " + header.getValue());
        }
        System.out.println();
        System.out.println(actualResponseBody);

        // Validate the response
        assertEquals("Incorrect response status", response.status, status.getStatusCode());
        assertEquals("Incorrect status message", response.message, status.getReasonPhrase());
        assertEquals("Incorrect response HTTP version", response.version,
                status.getProtocolVersion().toString());
        for (HeaderConfig header : response.headers) {
            assertEquals("Incorrect response header '" + header.name + "'", header.value,
                    methodResponse.getFirstHeader(header.name).getValue());
        }
        assertEquals("Incorrect response body", response.body, actualResponseBody);
    }
}

From source file:com.pyj.http.AsyncHttpClient.java

protected void sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest,
        String contentType, AsyncHttpResponseHandler responseHandler, Context context) {
    if (contentType != null) {
        uriRequest.addHeader("Content-Type", contentType);
    }/*w w  w.ja v  a2s.c om*/

    Future<?> request = threadPool.submit(
            new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler, responseHandler.reqCode));

    if (context != null) {
        // Add request to request map
        List<WeakReference<Future<?>>> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<WeakReference<Future<?>>>();
            requestMap.put(context, requestList);
        }

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }
}

From source file:com.waltz3d.common.httpclient.AsyncHttpClient.java

protected void sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest,
        String contentType, AsyncHttpResponseHandler responseHandler, Context context) {
    if (contentType != null) {
        uriRequest.addHeader("Content-Type", contentType);
    }/*www . j a  va 2  s. co m*/

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));
    if (context != null) {
        // Add request to request map
        List<WeakReference<Future<?>>> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<WeakReference<Future<?>>>();
            requestMap.put(context, requestList);
        }

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }
}

From source file:com.betfair.application.services.BaselineAppServiceTest.java

private String makeRequest(HttpCallable call, Object[] paramValues, int size, String contentType,
        Map<String, String> headersToAdd, Map<String, String> expectedReturnedHeaders) throws Exception {
    String result = null;//from   w  ww.  java2  s .c  o  m
    HttpClient httpc = new DefaultHttpClient();
    HttpCallLogEntry cle = new HttpCallLogEntry();
    HttpUriRequest method = call.getMethod(contentType, paramValues, size, cle);

    if (headersToAdd != null) {
        for (Map.Entry<String, String> entry : headersToAdd.entrySet()) {
            method.addHeader(entry.getKey(), entry.getValue());
        }
    }

    InputStream inputStream = null;

    try {
        final HttpResponse httpResponse = httpc.execute(method);
        int statusCode = httpResponse.getStatusLine().getStatusCode();

        int expectedHTTPCode = call.expectedResult();
        if (contentType.equals("SOAP") && expectedHTTPCode != HttpStatus.SC_OK) {
            // All SOAP errors are 500.
            expectedHTTPCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        }
        assertEquals(expectedHTTPCode, statusCode);

        if (expectedReturnedHeaders != null) {
            for (Map.Entry<String, String> entry : expectedReturnedHeaders.entrySet()) {
                Header h = httpResponse.getFirstHeader(entry.getKey());
                if (h == null) {
                    assertNull(entry.getValue());
                } else {
                    String headerValue = h.getValue();
                    assertEquals(entry.getValue(), headerValue);
                }
            }
        }

        // Read the response body.
        InputStream is = httpResponse.getEntity().getContent();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int b;
        while ((b = is.read()) != -1) {
            baos.write(b);
        }
        is.close();
        result = new String(baos.toByteArray(), CHARSET);

    } finally {
        // Release the connection.
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                /* ignore */ }
        }
    }
    return result;
}

From source file:org.doctester.testbrowser.TestBrowserImpl.java

private Response makeHeadGetOrDeleteRequest(Request request) {

    Response response;/*  ww w.ja  v  a 2s  . c om*/

    org.apache.http.HttpResponse apacheHttpClientResponse;

    try {

        HttpUriRequest apacheHttpRequest;

        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        if (GET.equalsIgnoreCase(request.httpRequestType)) {

            apacheHttpRequest = new HttpGet(request.uri);

        } else if (DELETE.equalsIgnoreCase(request.httpRequestType)) {

            apacheHttpRequest = new HttpDelete(request.uri);

        } else {

            apacheHttpRequest = new HttpHead(request.uri);

        }

        if (request.headers != null) {

            // add all headers
            for (Entry<String, String> header : request.headers.entrySet()) {
                apacheHttpRequest.addHeader(header.getKey(), header.getValue());
            }

        }

        setHandleRedirect(apacheHttpRequest, request.followRedirects);

        apacheHttpClientResponse = httpClient.execute(apacheHttpRequest);

        response = convertFromApacheHttpResponseToDocTesterHttpResponse(apacheHttpClientResponse);

        if (apacheHttpRequest instanceof HttpRequestBase) {
            ((HttpRequestBase) apacheHttpRequest).releaseConnection();
        }

    } catch (IOException e) {
        logger.error("Fatal problem creating GET or DELETE request in TestBrowser", e);
        throw new RuntimeException(e);
    }

    return response;
}

From source file:com.robustaweb.library.rest.client.implementation.ApacheRestClient.java

@Override
protected String executeMethod(HttpMethod method, String url, String requestBody) throws HttpException {
    assert url.startsWith("http");

    try {//  w  w  w  .j ava2 s.c  o  m
        client = createClient();
        HttpUriRequest httpMethod = null;

        switch (method) {
        case GET:
            httpMethod = new HttpGet(url);
            break;
        case DELETE:
            httpMethod = new HttpDelete(url);
            break;

        case POST:
            httpMethod = new HttpPost(url);
            ((HttpPost) httpMethod).setEntity(new StringEntity(this.requestBody));
            break;
        case PUT:
            httpMethod = new HttpPut(url);
            ((HttpPut) httpMethod).setEntity(new StringEntity(this.requestBody));
            break;
        default:
            throw new IllegalStateException("Can't execute this method : " + method);
        }

        //Adding headers
        if (this.contentType == null) {
            this.contentType = SynchronousRestClient.xmlContentType;
        }
        httpMethod.addHeader("Content-type", this.contentType);
        if (authorizationValue != null) {
            httpMethod.addHeader("Authorization", ApacheRestClient.authorizationValue);
        }

        //Executing
        HttpResponse httpResponse = client.execute(httpMethod);

        //parsing responseHeaders

        HeaderIterator it = httpResponse.headerIterator();
        while (it.hasNext()) {
            Header header = it.nextHeader();
            responseHeaders.put(header.getName(), header.getValue());
        }

        //Parsing response
        this.response = FileUtils.readInputStream(httpResponse.getEntity().getContent());

        return this.response;

    } catch (IOException ex) {
        throw new HttpException("IO Exception : " + ex.getMessage(), ex);
    } finally {
        clear();
    }
}

From source file:org.urbanstew.soundcloudapi.SoundCloudAPI.java

/**
  * Prepares and signs a request./*w  ww.j  av  a  2  s  .  c  om*/
 * @throws OAuthExpectationFailedException 
 * @throws OAuthMessageSignerException 
 * @throws OAuthCommunicationException 
  */
private HttpUriRequest signRequest(HttpUriRequest request)
        throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException {
    if (mOptions.version == OAuthVersion.V2_0 && mState == State.AUTHORIZED)
        request.addHeader("Authorization", "OAuth " + getToken());
    else
        getConsumer().sign(request);
    return request;
}

From source file:com.example.wechatsample.library.http.AsyncHttpClient.java

/********************************************************************************************************/

// Private stuff/*from   w w w.  j  a v a  2 s  .  co m*/
protected void sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest,
        String contentType, AsyncHttpResponseHandler responseHandler, Context context) {
    if (contentType != null) {
        uriRequest.addHeader("Content-Type", contentType);
    }

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

    if (context != null) {
        // Add request to request map
        List<WeakReference<Future<?>>> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<WeakReference<Future<?>>>();
            requestMap.put(context, requestList);
        }

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }
}

From source file:cn.edu.zzu.wemall.http.AsyncHttpClient.java

/**
 * Puts a new request in queue as a new thread in pool to be executed
 *
 * @param client          HttpClient to be used for request, can differ in single requests
 * @param contentType     MIME body type, for POST and PUT requests, may be null
 * @param context         Context of Android application, to hold the reference of request
 * @param httpContext     HttpContext in which the request will be executed
 * @param responseHandler ResponseHandler or its subclass to put the response into
 * @param uriRequest      instance of HttpUriRequest, which means it must be of HttpDelete, HttpPost, HttpGet, HttpPut, etc.
 */// www.  ja  va2s.  c  o m
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, AsyncHttpResponseHandler responseHandler,
        Context context) {
    if (contentType != null) {
        uriRequest.addHeader("Content-Type", contentType);
    }

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

    if (context != null) {
        // Add request to request map
        List<WeakReference<Future<?>>> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<WeakReference<Future<?>>>();
            requestMap.put(context, requestList);
        }

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }

    return new RequestHandle(request);
}