Example usage for org.apache.http.message BasicHttpRequest BasicHttpRequest

List of usage examples for org.apache.http.message BasicHttpRequest BasicHttpRequest

Introduction

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

Prototype

public BasicHttpRequest(String str, String str2) 

Source Link

Usage

From source file:ste.web.http.beanshell.BugFreeBeanShellUtils.java

@Test
public void cleanup() throws Exception {
    BasicHttpRequest request = new BasicHttpRequest("get", TEST_URI_PARAMETERS);
    HttpSessionContext context = new HttpSessionContext();
    context.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection());
    context.setAttribute(TEST_REQ_ATTR_NAME1, TEST_VALUE1);

    Interpreter i = new Interpreter();
    BeanShellUtils.setup(i, request, RESPONSE_OK, context);
    BeanShellUtils.cleanup(i, request);/* w w  w . j  ava 2  s .  c  o m*/

    //
    // We need to make sure that after the handling of the request,
    // parameters are not valid variable any more so to avoid that next
    // invocations will inherit them
    //
    checkCleanup(i, QueryString.parse(new URI(request.getRequestLine().getUri())).getNames());
}

From source file:securitydigest.TestDigestScheme.java

public void testDigestAuthenticationWithDefaultCreds() throws Exception {
    String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
    Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
    HttpRequest request = new BasicHttpRequest("Simple", "/");
    Credentials cred = new UsernamePasswordCredentials("username", "password");
    AuthScheme authscheme = new DigestScheme();
    authscheme.processChallenge(authChallenge);
    Header authResponse = authscheme.authenticate(cred, request);

    Map<String, String> table = parseAuthResponse(authResponse);
    assertEquals("username", table.get("username"));
    assertEquals("realm1", table.get("realm"));
    assertEquals("/", table.get("uri"));
    assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
    assertEquals("e95a7ddf37c2eab009568b1ed134f89a", table.get("response"));
}

From source file:com.uber.jaeger.httpclient.JaegerRequestAndResponseInterceptorIntegrationTest.java

@Test
public void testAsyncHttpClientTracing() throws Exception {
    HttpAsyncClientBuilder clientBuilder = HttpAsyncClients.custom();
    CloseableHttpAsyncClient client = TracingInterceptors.addTo(clientBuilder, tracer).build();

    client.start();/*from w w  w .ja  v  a 2 s  . c o m*/

    //Make a request to the async client and wait for response
    client.execute(new HttpHost("localhost", mockServerRule.getPort()), new BasicHttpRequest("GET", "/testing"),
            new FutureCallback<org.apache.http.HttpResponse>() {
                @Override
                public void completed(org.apache.http.HttpResponse result) {
                }

                @Override
                public void failed(Exception ex) {
                }

                @Override
                public void cancelled() {
                }
            }).get();

    verifyTracing(parentSpan);
}

From source file:org.uiautomation.ios.server.grid.SelfRegisteringRemote.java

private boolean isAlreadyRegistered() {
    HttpClient client = httpClientFactory.getHttpClient();
    try {/*from  ww  w.  ja v  a2s . c o m*/
        URL hubRegistrationURL = new URL(nodeConfig.getRegistrationURL());
        URL api = new URL("http://" + hubRegistrationURL.getHost() + ":" + hubRegistrationURL.getPort()
                + "/grid/api/proxy");
        HttpHost host = new HttpHost(api.getHost(), api.getPort());

        String id = "http://" + nodeConfig.getHost() + ":" + nodeConfig.getPort();
        BasicHttpRequest r = new BasicHttpRequest("GET", api.toExternalForm() + "?id=" + id);

        HttpResponse response = client.execute(host, r);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new GridException(
                    "hub down or not responding. Reason : " + response.getStatusLine().getReasonPhrase());
        }
        JSONObject o = extractObject(response);
        return (Boolean) o.get("success");
    } catch (Exception e) {
        throw new GridException("Problem registering with hub", e);
    }
}

From source file:com.devoteam.srit.xmlloader.http.test.HttpLoaderServer.java

public void sendRequest(String method, String uri, HttpParams params) throws IOException {
    // Required protocol interceptors
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    // Recommended protocol interceptors
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, Clientconn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, hostname);
    try {// w  w  w . j a v a2s  .  c  om
        testConnection();
        BasicHttpRequest br = new BasicHttpRequest(method, uri);
        context.setAttribute(ExecutionContext.HTTP_REQUEST, br);
        br.setParams(params);
        //myclass.doSendRequest(br, Clientconn, context);
    } catch (Exception e) {
    }

}

From source file:org.overlord.apiman.service.client.http.HTTPServiceClient.java

/**
 * {@inheritDoc}//from ww  w .java  2 s.c om
 */
@Override
public Response process(Request request) throws Exception {
    String method = "GET";

    if (request instanceof HTTPGatewayRequest) {
        method = ((HTTPGatewayRequest) request).getHTTPMethod();
    }

    String proxyRequestUri = rewriteUrlFromRequest(request);

    HttpRequest proxyRequest;

    //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
    if (request.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || request.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);

        java.io.InputStream is = new java.io.ByteArrayInputStream(request.getContent());

        InputStreamEntity entity = new InputStreamEntity(is, request.getContent().length);

        is.close();

        eProxyRequest.setEntity(entity);

        proxyRequest = eProxyRequest;
    } else {
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }

    copyRequestHeaders(request, proxyRequest);

    try {
        // Execute the request
        if (LOG.isLoggable(Level.FINER)) {
            LOG.finer("proxy " + method + " uri: " + request.getSourceURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }

        HttpResponse proxyResponse = _proxyClient
                .execute(URIUtils.extractHost(new java.net.URI(request.getServiceURI())), proxyRequest);

        Response resp = new HTTPGatewayResponse(proxyResponse);

        return (resp);

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        //noinspection ConstantConditions
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new RuntimeException(e);
    }
}

From source file:org.mycard.net.network.Request.java

/***
 * Instantiates a new Request.//from   ww w .ja v  a2  s.c o  m
 * @param method GET/POST/PUT
 * @param host The server that will handle this request
 * @param path path part of URI
 * @param bodyProvider InputStream providing HTTP body, null if none
 * @param bodyLength length of body, must be 0 if bodyProvider is null
 * @param eventHandler request will make progress callbacks on
 * this interface
 * @param headers reqeust headers
 */
Request(String method, HttpHost host, HttpHost proxyHost, String path, InputStream bodyProvider, int bodyLength,
        EventHandler eventHandler, Map<String, String> headers) {
    mEventHandler = eventHandler;
    mHost = host;
    mProxyHost = proxyHost;
    mPath = path;
    mBodyProvider = bodyProvider;
    mBodyLength = bodyLength;

    if (bodyProvider == null && !"POST".equalsIgnoreCase(method)) {
        mHttpRequest = new BasicHttpRequest(method, getUri());
        setReceivedContentRange(headers);
    } else {
        mHttpRequest = new BasicHttpEntityEnclosingRequest(method, getUri());
        // it is ok to have null entity for BasicHttpEntityEnclosingRequest.
        // By using BasicHttpEntityEnclosingRequest, it will set up the
        // correct content-length, content-type and content-encoding.
        if (bodyProvider != null) {
            setBodyProvider(bodyProvider, bodyLength);
        }
    }
    addHeader(HOST_HEADER, getHostPort());

    /** FIXME: if webcore will make the root document a
       high-priority request, we can ask for gzip encoding only on
       high priority reqs (saving the trouble for images, etc) */
    addHeader(ACCEPT_ENCODING_HEADER, "gzip");
    addHeaders(headers);
}

From source file:android.net.http.Request.java

/**
 * Instantiates a new Request.//from  w  w w.ja  v  a  2 s . c om
 * @param method GET/POST/PUT
 * @param host The server that will handle this request
 * @param path path part of URI
 * @param bodyProvider InputStream providing HTTP body, null if none
 * @param bodyLength length of body, must be 0 if bodyProvider is null
 * @param eventHandler request will make progress callbacks on
 * this interface
 * @param headers reqeust headers
 */
Request(String method, HttpHost host, HttpHost proxyHost, String path, InputStream bodyProvider, int bodyLength,
        EventHandler eventHandler, Map<String, String> headers) {
    mEventHandler = eventHandler;
    mHost = host;
    mProxyHost = proxyHost;
    mPath = path;
    mBodyProvider = bodyProvider;
    mBodyLength = bodyLength;

    if (bodyProvider == null && !"POST".equalsIgnoreCase(method)) {
        mHttpRequest = new BasicHttpRequest(method, getUri());
    } else {
        mHttpRequest = new BasicHttpEntityEnclosingRequest(method, getUri());
        // it is ok to have null entity for BasicHttpEntityEnclosingRequest.
        // By using BasicHttpEntityEnclosingRequest, it will set up the
        // correct content-length, content-type and content-encoding.
        if (bodyProvider != null) {
            setBodyProvider(bodyProvider, bodyLength);
        }
    }
    addHeader(HOST_HEADER, getHostPort());

    /* FIXME: if webcore will make the root document a
       high-priority request, we can ask for gzip encoding only on
       high priority reqs (saving the trouble for images, etc) */
    addHeader(ACCEPT_ENCODING_HEADER, "gzip");
    addHeaders(headers);
}

From source file:org.ebayopensource.twin.TwinConnection.java

@SuppressWarnings("unchecked")
private Map<String, Object> _request(String method, String path, Map<String, Object> body,
        JSONRecognizer... recognizers) throws IOException, TwinException {
    String uri = url + path;/* w  ww.  jav a 2s .c om*/
    HttpRequest request;
    if (body == null) {
        BasicHttpRequest r = new BasicHttpRequest(method, uri);
        request = r;
    } else {
        BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(method, uri);
        StringEntity entity;
        try {
            entity = new StringEntity(JSON.encode(body), "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        entity.setContentType("application/json; charset=utf-8");
        r.setEntity(entity);
        request = r;
    }

    HttpClient client = getClient();
    try {
        HttpResponse response = client.execute(new HttpHost(url.getHost(), url.getPort()), request);
        HttpEntity entity = response.getEntity();
        if (entity == null)
            return null;
        String contentType = entity.getContentType().getValue();
        boolean isJson = (contentType != null)
                && ("application/json".equals(contentType) || contentType.startsWith("application/json;"));
        String result = null;

        InputStream in = entity.getContent();
        try {
            Reader r = new InputStreamReader(in, "UTF-8");
            StringBuilder sb = new StringBuilder();
            char[] buf = new char[256];
            int read;
            while ((read = r.read(buf, 0, buf.length)) >= 0)
                sb.append(buf, 0, read);
            r.close();

            result = sb.toString();
        } finally {
            try {
                in.close();
            } catch (Exception e) {
            }
        }

        int code = response.getStatusLine().getStatusCode();
        if (code >= 400) {
            if (isJson) {
                try {
                    throw deserializeException((Map<String, Object>) JSON.decode(result));
                } catch (IllegalArgumentException e) {
                    throw TwinError.UnknownError.create("Couldn't parse error response: \n" + result, e);
                }
            }
            if (code == 404)
                throw TwinError.UnknownCommand.create("Got server response " + code + " for request " + uri);
            else
                throw TwinError.UnknownError
                        .create("Got server response " + code + " for request " + uri + "\nBody is " + result);
        }

        if (!isJson)
            throw TwinError.UnknownError.create(
                    "Got wrong content type " + contentType + " for request " + uri + "\nBody is " + result);

        try {
            return (Map<String, Object>) JSON.decode(result, recognizers);
        } catch (Exception e) {
            throw TwinError.UnknownError
                    .create("Malformed JSON result for request " + uri + ": \nBody is " + result, e);
        }
    } catch (ClientProtocolException e) {
        throw new IOException(e);
    }
}

From source file:proxy.ElementalHttpGet.java

private static void request(HttpProcessor httpproc, HttpRequestExecutor httpexecutor,
        HttpCoreContext coreContext, HttpHost host, InetAddress localinetAddress)
        throws NoSuchAlgorithmException, IOException, HttpException {
    DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
    ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;
    try {//from  w ww  .j a  v  a  2 s .  c om

        String[] targets = { "/2/users/show.json?access_token=2.00SlDQsDdcZIJC94e5308f67sRL13D&uid=3550148352",
                "/account/rate_limit_status.json?access_token=2.00SlDQsDdcZIJC94e5308f67sRL13D" };

        for (int i = 0; i < targets.length; i++) {
            if (!conn.isOpen()) {
                SSLContext sslcontext = SSLContext.getInstance("Default");
                //               sslcontext.init(null, null, null);
                SocketFactory sf = sslcontext.getSocketFactory();
                SSLSocket socket = (SSLSocket) sf.createSocket(host.getHostName(), host.getPort(),
                        localinetAddress, 0);
                socket.setEnabledCipherSuites(new String[] { "TLS_RSA_WITH_AES_256_CBC_SHA",
                        "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" });
                conn.bind(socket);
                //               Socket socket = new Socket(host.getHostName(), host.getPort());
                //               conn.bind(socket);
            }
            BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            httpexecutor.preProcess(request, httpproc, coreContext);
            HttpResponse response = httpexecutor.execute(request, conn, coreContext);
            httpexecutor.postProcess(response, httpproc, coreContext);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, coreContext)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}