Search in sources :

Example 66 with HttpResponse

use of org.apache.http.HttpResponse in project selenium-tests by Wikia.

the class CommonUtils method sendPost.

public static String sendPost(String apiUrl, String[][] param) {
    try {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(apiUrl);
        List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();
        for (int i = 0; i < param.length; i++) {
            paramPairs.add(new BasicNameValuePair(param[i][0], param[i][1]));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(paramPairs));
        HttpResponse response = null;
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity);
    } catch (UnsupportedEncodingException e) {
        PageObjectLogging.log("sendPost", e, false);
        return null;
    } catch (ClientProtocolException e) {
        PageObjectLogging.log("sendPost", e, false);
        return null;
    } catch (IOException e) {
        PageObjectLogging.log("sendPost", e, false);
        return null;
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair)

Example 67 with HttpResponse

use of org.apache.http.HttpResponse in project voltdb by VoltDB.

the class TestJSONOverHttps method callProcOverJSON.

private String callProcOverJSON(String varString, final int expectedCode) throws Exception {
    URI uri = URI.create("https://localhost:" + m_port + "/api/1.0/");
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sf).build();
    // allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClientBuilder b = HttpClientBuilder.create();
    b.setSslcontext(sslContext);
    b.setConnectionManager(connMgr);
    try (CloseableHttpClient httpclient = b.build()) {
        HttpPost post = new HttpPost(uri);
        // play nice by using HTTP 1.1 continue requests where the client sends the request headers first
        // to the server to see if the server is willing to accept it. This allows us to test large requests
        // without incurring server socket connection terminations
        RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setExpectContinueEnabled(true).build();
        post.setProtocolVersion(HttpVersion.HTTP_1_1);
        post.setConfig(rc);
        post.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
        ResponseHandler<String> rh = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                assertEquals(expectedCode, status);
                if ((status >= 200 && status < 300) || status == 400) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                }
                return null;
            }
        };
        return httpclient.execute(post, rh);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) URI(java.net.URI) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) StringEntity(org.apache.http.entity.StringEntity) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder)

Example 68 with HttpResponse

use of org.apache.http.HttpResponse in project hadoop-pcap by RIPE-NCC.

the class HttpPcapReader method processPacketPayload.

@Override
protected void processPacketPayload(Packet packet, final byte[] payload) {
    String protocol = (String) packet.get(Packet.PROTOCOL);
    if (!PcapReader.PROTOCOL_TCP.equals(protocol))
        return;
    HttpPacket httpPacket = (HttpPacket) packet;
    Integer srcPort = (Integer) packet.get(Packet.SRC_PORT);
    Integer dstPort = (Integer) packet.get(Packet.DST_PORT);
    if ((HTTP_PORT == srcPort || HTTP_PORT == dstPort) && packet.containsKey(Packet.REASSEMBLED_TCP_FRAGMENTS)) {
        final SessionInputBuffer inBuf = new AbstractSessionInputBuffer() {

            {
                init(new ByteArrayInputStream(payload), 1024, params);
            }

            @Override
            public boolean isDataAvailable(int timeout) throws IOException {
                return true;
            }
        };
        final SessionOutputBuffer outBuf = new AbstractSessionOutputBuffer() {
        };
        if (HTTP_PORT == srcPort) {
            HttpMessageParser<HttpResponse> parser = new DefaultHttpResponseParser(inBuf, null, respFactory, params);
            HttpClientConnection conn = new DefaultClientConnection() {

                {
                    init(inBuf, outBuf, params);
                }

                @Override
                protected void assertNotOpen() {
                }

                @Override
                protected void assertOpen() {
                }
            };
            try {
                HttpResponse response = parser.parse();
                conn.receiveResponseEntity(response);
                propagateHeaders(httpPacket, response.getAllHeaders());
            } catch (IOException e) {
                LOG.error("IOException when decoding HTTP response", e);
            } catch (HttpException e) {
                LOG.error("HttpException when decoding HTTP response", e);
            }
        } else if (HTTP_PORT == dstPort) {
            HttpMessageParser<HttpRequest> parser = new DefaultHttpRequestParser(inBuf, null, reqFactory, params);
            try {
                HttpRequest request = parser.parse();
                propagateHeaders(httpPacket, request.getAllHeaders());
            } catch (IOException e) {
                LOG.error("IOException when decoding HTTP request", e);
            } catch (HttpException e) {
                LOG.error("HttpException when decoding HTTP request", e);
            }
        }
    }
}
Also used : HttpRequest(org.apache.http.HttpRequest) SessionInputBuffer(org.apache.http.io.SessionInputBuffer) AbstractSessionInputBuffer(org.apache.http.impl.io.AbstractSessionInputBuffer) DefaultClientConnection(org.apache.http.impl.conn.DefaultClientConnection) HttpPacket(net.ripe.hadoop.pcap.packet.HttpPacket) HttpClientConnection(org.apache.http.HttpClientConnection) HttpMessageParser(org.apache.http.io.HttpMessageParser) HttpResponse(org.apache.http.HttpResponse) AbstractSessionInputBuffer(org.apache.http.impl.io.AbstractSessionInputBuffer) IOException(java.io.IOException) SessionOutputBuffer(org.apache.http.io.SessionOutputBuffer) AbstractSessionOutputBuffer(org.apache.http.impl.io.AbstractSessionOutputBuffer) ByteArrayInputStream(java.io.ByteArrayInputStream) DefaultHttpResponseParser(org.apache.http.impl.io.DefaultHttpResponseParser) AbstractSessionOutputBuffer(org.apache.http.impl.io.AbstractSessionOutputBuffer) HttpException(org.apache.http.HttpException) DefaultHttpRequestParser(org.apache.http.impl.io.DefaultHttpRequestParser)

Example 69 with HttpResponse

use of org.apache.http.HttpResponse in project java-chassis by ServiceComb.

the class HttpsClient method get.

private static HttpResponse get(HttpClient httpClient, String url, Map<String, String> headers) throws ClientProtocolException, IOException {
    HttpGet getRequest = new HttpGet(url);
    for (Entry<String, String> header : headers.entrySet()) {
        getRequest.addHeader(header.getKey(), header.getValue());
    }
    HttpResponse response = httpClient.execute(getRequest);
    return response;
}
Also used : HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse)

Example 70 with HttpResponse

use of org.apache.http.HttpResponse in project java-chassis by ServiceComb.

the class TestHttpsClient method testHttpClient.

@Test
public void testHttpClient() throws ClientProtocolException, IOException {
    // test valid Invalid Inputs
    Map<String, String> oHeaders = new HashMap<String, String>();
    oHeaders.put("X-Auth", "JHGUGJGH");
    HttpResponse oResponse = HttpsClient.execute("UNKNOWN METHOD", oHeaders, "//check", "body", null);
    Assert.assertEquals(null, oResponse);
    oResponse = HttpsClient.execute("", oHeaders, "//check", "body", null);
    Assert.assertEquals(null, oResponse);
    oResponse = HttpsClient.execute("UNKNOWN METHOD", oHeaders, "", "body", null);
    Assert.assertEquals(null, oResponse);
    oResponse = HttpsClient.execute("UNKNOWN METHOD", null, "//check", "body", null);
    Assert.assertEquals(null, oResponse);
    // With default Bean
    HttpsConfigInfoBean oBean = new HttpsConfigInfoBean();
    oBean.setKeyStorePath("JHGJ");
    oBean.setKeyStorePasswd("HJGJH");
    oBean.setTrustStorePasswd("JHGJHG");
    oBean.setTrustStorePath("JHGJGj");
    Assert.assertEquals("JHGJGj", oBean.getTrustStorePath());
    Assert.assertEquals("JHGJHG", oBean.getTrustStorePasswd());
    oResponse = HttpsClient.execute("UNKNOWN METHOD", oHeaders, "//check", "body", oBean);
    Assert.assertEquals(null, oResponse);
    HttpsClient.getHttpsClient(oBean);
    Assert.assertNotEquals(null, HttpsClient.getHttpsClient(Mockito.mock(HttpsConfigInfoBean.class)));
    //Handle Error Scenarios
    try {
        oResponse = HttpsClient.execute("POST", oHeaders, "//check", "body", oBean);
    } catch (Exception e) {
        Assert.assertEquals("Target host is null", e.getMessage());
    }
    try {
        oResponse = HttpsClient.execute("GET", oHeaders, "//check", "body", oBean);
    } catch (Exception e) {
        Assert.assertEquals("Target host is null", e.getMessage());
    }
    try {
        oResponse = HttpsClient.execute("DELETE", oHeaders, "//check", "body", oBean);
    } catch (Exception e) {
        Assert.assertEquals("Target host is null", e.getMessage());
    }
// TODO Check the valid Responses
}
Also used : HashMap(java.util.HashMap) HttpResponse(org.apache.http.HttpResponse) HttpsConfigInfoBean(io.servicecomb.foundation.common.entities.HttpsConfigInfoBean) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Test(org.junit.Test)

Aggregations

HttpResponse (org.apache.http.HttpResponse)4168 Test (org.junit.Test)2110 HttpGet (org.apache.http.client.methods.HttpGet)1770 IOException (java.io.IOException)1000 URI (java.net.URI)817 HttpPost (org.apache.http.client.methods.HttpPost)699 HttpClient (org.apache.http.client.HttpClient)550 HttpEntity (org.apache.http.HttpEntity)496 TestHttpClient (io.undertow.testutils.TestHttpClient)403 InputStream (java.io.InputStream)373 Header (org.apache.http.Header)370 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)333 StringEntity (org.apache.http.entity.StringEntity)332 HttpPut (org.apache.http.client.methods.HttpPut)310 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)307 ArrayList (java.util.ArrayList)296 Identity (org.olat.core.id.Identity)262 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)237 File (java.io.File)192 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)191