Example usage for org.apache.http.client.methods HttpPost getEntity

List of usage examples for org.apache.http.client.methods HttpPost getEntity

Introduction

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

Prototype

public HttpEntity getEntity() 

Source Link

Usage

From source file:com.aliyun.oss.common.comm.HttpFactoryTest.java

@Test
public void testCreateHttpRequest() throws Exception {
    ExecutionContext context = new ExecutionContext();
    String url = "http://127.0.0.1";
    String content = "This is a test request";
    byte[] contentBytes = null;
    try {/* w  ww  .  jav  a  2 s  . co  m*/
        contentBytes = content.getBytes(context.getCharset());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

    HttpRequestFactory factory = new HttpRequestFactory();

    ServiceClient.Request request = new ServiceClient.Request();
    request.setUrl(url);

    HttpRequestBase httpRequest = null;

    // GET
    request.setMethod(HttpMethod.GET);
    httpRequest = factory.createHttpRequest(request, context);
    HttpGet getMethod = (HttpGet) httpRequest;
    assertEquals(url, getMethod.getURI().toString());

    // DELETE
    request.setMethod(HttpMethod.DELETE);
    httpRequest = factory.createHttpRequest(request, context);
    HttpDelete delMethod = (HttpDelete) httpRequest;
    assertEquals(url, delMethod.getURI().toString());

    // HEAD
    request.setMethod(HttpMethod.HEAD);
    httpRequest = factory.createHttpRequest(request, context);
    HttpHead headMethod = (HttpHead) httpRequest;
    assertEquals(url, headMethod.getURI().toString());

    //POST
    request.setContent(new ByteArrayInputStream(contentBytes));
    request.setContentLength(contentBytes.length);
    request.setMethod(HttpMethod.POST);
    httpRequest = factory.createHttpRequest(request, context);
    HttpPost postMethod = (HttpPost) httpRequest;

    assertEquals(url, postMethod.getURI().toString());
    HttpEntity entity = postMethod.getEntity();

    try {
        assertEquals(content, readSting(entity.getContent()));
    } catch (IllegalStateException e) {
        e.printStackTrace();
        fail(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

    //PUT
    request.setContent(new ByteArrayInputStream(contentBytes));
    request.setContentLength(contentBytes.length);
    request.setMethod(HttpMethod.PUT);
    httpRequest = factory.createHttpRequest(request, context);
    HttpPut putMethod = (HttpPut) httpRequest;

    assertEquals(url, putMethod.getURI().toString());
    entity = putMethod.getEntity();
    try {
        assertEquals(content, readSting(entity.getContent()));
    } catch (IllegalStateException e) {
        e.printStackTrace();
        fail(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

    try {
        request.close();
    } catch (IOException e) {
    }
}

From source file:tech.sirwellington.alchemy.http.AlchemyRequestMapperTest.java

@Test
public void testPostWithBody() throws Exception {
    instance = AlchemyRequestMapper.POST;

    when(request.hasBody()).thenReturn(true);

    HttpUriRequest result = instance.convertToApacheRequest(request);
    assertThat(result, instanceOf(HttpPost.class));

    HttpPost post = (HttpPost) result;
    assertEntity(post.getEntity());
}

From source file:com.nominanuda.web.http.SerializeDeserializeTest.java

@Test
public void testRequest() throws IOException, HttpException {
    HttpPost req = new HttpPost(REQ_URI);
    req.addHeader("h1", "v1");
    req.setEntity(new StringEntity(PAYLOAD, ContentType.create("text/plain", "UTF-8")));
    byte[] serialized = HTTP.serialize(req);
    //System.err.println(new String(serialized, "UTF-8"));
    HttpPost m = (HttpPost) HTTP.deserialize(new ByteArrayInputStream(serialized));
    //System.err.println(new String(HTTP.serialize(m), "UTF-8"));
    assertEquals(REQ_URI, m.getRequestLine().getUri());
    assertEquals(PAYLOAD.getBytes(HttpProtocol.CS_UTF_8).length,
            ((ByteArrayEntity) m.getEntity()).getContentLength());
    assertEquals("v1", m.getFirstHeader("h1").getValue());
}

From source file:org.onebusaway.siri.core.SiriClientTest.java

@Test
public void testHandleRequestWithResponseForCheckStatusRequestAndResponse()
        throws IllegalStateException, IOException, XpathException, SAXException {

    SiriClientRequest request = new SiriClientRequest();
    request.setTargetUrl("http://localhost/");
    request.setTargetVersion(ESiriVersion.V1_3);

    Siri payload = new Siri();
    request.setPayload(payload);/*w  w  w .  ja  va  2  s .c om*/

    CheckStatusRequestStructure checkStatusRequest = new CheckStatusRequestStructure();
    payload.setCheckStatusRequest(checkStatusRequest);

    StringBuilder b = new StringBuilder();
    b.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
    b.append("<Siri xmlns=\"http://www.siri.org.uk/siri\" version=\"1.3\">");
    b.append("  <CheckStatusResponse>");
    b.append("  </CheckStatusResponse>");
    b.append("</Siri>");

    HttpResponse response = createResponse();
    response.setEntity(new StringEntity(b.toString()));

    Mockito.when(_httpClientService.executeHttpMethod(Mockito.any(HttpClient.class),
            Mockito.any(HttpUriRequest.class))).thenReturn(response);

    Siri siriResponse = _client.handleRequestWithResponse(request);

    /**
     * Verify that the http client was called and capture the request
     */
    ArgumentCaptor<HttpUriRequest> captor = ArgumentCaptor.forClass(HttpUriRequest.class);
    Mockito.verify(_httpClientService).executeHttpMethod(Mockito.any(HttpClient.class), captor.capture());

    /**
     * Verify that our CheckStatusResponse was properly passed on to the
     * subscription manager
     */
    Mockito.verify(_subscriptionManager)
            .handleCheckStatusNotification(Mockito.any(CheckStatusResponseStructure.class));

    /**
     * Verify the raw parameters of the request
     */
    HttpUriRequest uriRequest = captor.getValue();
    assertEquals("http://localhost/", uriRequest.getURI().toString());
    assertEquals("POST", uriRequest.getMethod());

    /**
     * Verify the request content
     */
    HttpPost post = (HttpPost) uriRequest;
    HttpEntity entity = post.getEntity();
    String content = getHttpEntityAsString(entity);
    Document doc = XMLUnit.buildControlDocument(content);

    assertXpathExists("/s:Siri", doc);
    assertXpathEvaluatesTo("1.3", "/s:Siri/@version", doc);
    assertXpathExists("/s:Siri/s:CheckStatusRequest", content);
    assertXpathExists("/s:Siri/s:CheckStatusRequest/s:RequestTimestamp", doc);
    assertXpathExists("/s:Siri/s:CheckStatusRequest/s:Address", doc);
    assertXpathEvaluatesTo("somebody", "/s:Siri/s:CheckStatusRequest/s:RequestorRef", doc);
    assertXpathExists("/s:Siri/s:CheckStatusRequest/s:MessageIdentifier", doc);

    // Verify that the message id is a UUID
    String messageId = evaluateXPath("/s:Siri/s:CheckStatusRequest/s:MessageIdentifier", doc);
    UUID.fromString(messageId);

    /**
     * Verify that the CheckStatusResponse was properly received and parsed
     */
    CheckStatusResponseStructure checkStatusResponse = siriResponse.getCheckStatusResponse();
    assertNotNull(checkStatusResponse);
}

From source file:dwhit.emerapp.RegistrationIntentService.java

/**
 * Persist registration to third-party servers.
 *
 * Modify this method to associate the user's GCM registration token with any server-side account
 * maintained by your application.//  w w w .j a  v  a 2  s . c  o m
 *
 * @param token The new token.
 */
private void sendRegistrationToServer(String token) {
    String USER_AGENT = "Mozilla/5.0";
    // TODO: currently this ip needs to be changed to wherever the server is being run.
    String url = "http://192.168.0.4:8080/api/reg?tok=" + token;
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);

    // add header
    post.setHeader("User-Agent", USER_AGENT);

    try {
        HttpResponse response = client.execute(post);
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + post.getEntity());
        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.liferay.ide.core.remote.RemoteConnection.java

protected Object httpJSONAPI(Object... args) throws APIException {
    if (!(args[0] instanceof HttpRequestBase)) {
        throw new IllegalArgumentException("First argument must be a HttpRequestBase."); //$NON-NLS-1$
    }/*from w  w w .  j a  va  2 s. c  o  m*/

    Object retval = null;
    String api = null;
    Object[] params = new Object[0];

    final HttpRequestBase request = (HttpRequestBase) args[0];

    final boolean isPostRequest = request instanceof HttpPost;

    if (args[1] instanceof String) {
        api = args[1].toString();
    } else if (args[1] instanceof Object[]) {
        params = (Object[]) args[1];
        api = params[0].toString();
    } else {
        throw new IllegalArgumentException("2nd argument must be either String or Object[]"); //$NON-NLS-1$
    }

    try {
        final URIBuilder builder = new URIBuilder();
        builder.setScheme("http"); //$NON-NLS-1$
        builder.setHost(getHost());
        builder.setPort(getHttpPort());
        builder.setPath(api);

        List<NameValuePair> postParams = new ArrayList<NameValuePair>();

        if (params.length >= 3) {
            for (int i = 1; i < params.length; i += 2) {
                String name = null;
                String value = StringPool.EMPTY;

                if (params[i] != null) {
                    name = params[i].toString();
                }

                if (params[i + 1] != null) {
                    value = params[i + 1].toString();
                }

                if (isPostRequest) {
                    postParams.add(new BasicNameValuePair(name, value));
                } else {
                    builder.setParameter(name, value);
                }
            }
        }

        if (isPostRequest) {
            HttpPost postRequest = ((HttpPost) request);

            if (postRequest.getEntity() == null) {
                postRequest.setEntity(new UrlEncodedFormEntity(postParams));
            }
        }

        request.setURI(builder.build());

        String response = getHttpResponse(request);

        if (response != null && response.length() > 0) {
            Object jsonResponse = getJSONResponse(response);

            if (jsonResponse == null) {
                throw new APIException(api, "Unable to get response: " + response); //$NON-NLS-1$
            } else {
                retval = jsonResponse;
            }
        }
    } catch (APIException e) {
        throw e;
    } catch (Exception e) {
        throw new APIException(api, e);
    } finally {
        try {
            request.releaseConnection();
        } finally {
            // no need to log error
        }
    }

    return retval;
}

From source file:org.apache.nifi.toolkit.tls.service.client.TlsCertificateSigningRequestPerformerTest.java

@Before
public void setup() throws GeneralSecurityException, OperatorCreationException, IOException {
    objectMapper = new ObjectMapper();
    keyPair = TlsHelper.generateKeyPair(TlsConfig.DEFAULT_KEY_PAIR_ALGORITHM, TlsConfig.DEFAULT_KEY_SIZE);

    testToken = "testTokenTestToken";
    testCaHostname = "testCaHostname";
    testPort = 8993;// w  ww .  j  av a  2 s .  co m
    certificates = new ArrayList<>();

    when(tlsClientConfig.getToken()).thenReturn(testToken);
    when(tlsClientConfig.getCaHostname()).thenReturn(testCaHostname);
    when(tlsClientConfig.getDn()).thenReturn(new TlsConfig().calcDefaultDn(testCaHostname));
    when(tlsClientConfig.getPort()).thenReturn(testPort);
    when(tlsClientConfig.createCertificateSigningRequestPerformer())
            .thenReturn(tlsCertificateSigningRequestPerformer);
    when(tlsClientConfig.getSigningAlgorithm()).thenReturn(TlsConfig.DEFAULT_SIGNING_ALGORITHM);
    JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = TlsHelper.generateCertificationRequest(
            tlsClientConfig.getDn(), null, keyPair, TlsConfig.DEFAULT_SIGNING_ALGORITHM);
    String testCsrPem = TlsHelper.pemEncodeJcaObject(jcaPKCS10CertificationRequest);
    when(httpClientBuilderSupplier.get()).thenReturn(httpClientBuilder);
    when(httpClientBuilder.build()).thenAnswer(invocation -> {
        Field sslSocketFactory = HttpClientBuilder.class.getDeclaredField("sslSocketFactory");
        sslSocketFactory.setAccessible(true);
        Object o = sslSocketFactory.get(httpClientBuilder);
        Field field = TlsCertificateAuthorityClientSocketFactory.class.getDeclaredField("certificates");
        field.setAccessible(true);
        ((List<X509Certificate>) field.get(o)).addAll(certificates);
        return closeableHttpClient;
    });
    StatusLine statusLine = mock(StatusLine.class);
    when(statusLine.getStatusCode()).thenAnswer(i -> statusCode);
    when(closeableHttpClient.execute(eq(new HttpHost(testCaHostname, testPort, "https")), any(HttpPost.class)))
            .thenAnswer(invocation -> {
                HttpPost httpPost = (HttpPost) invocation.getArguments()[1];
                TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = objectMapper
                        .readValue(httpPost.getEntity().getContent(), TlsCertificateAuthorityRequest.class);
                assertEquals(tlsCertificateAuthorityRequest.getCsr(), testCsrPem);
                CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
                when(closeableHttpResponse.getEntity()).thenAnswer(i -> {
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    objectMapper.writeValue(byteArrayOutputStream, tlsCertificateAuthorityResponse);
                    return new ByteArrayEntity(byteArrayOutputStream.toByteArray());
                });
                when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine);
                return closeableHttpResponse;
            });
    KeyPair caKeyPair = TlsHelper.generateKeyPair(TlsConfig.DEFAULT_KEY_PAIR_ALGORITHM,
            TlsConfig.DEFAULT_KEY_SIZE);
    caCertificate = CertificateUtils.generateSelfSignedX509Certificate(caKeyPair, "CN=fakeCa",
            TlsConfig.DEFAULT_SIGNING_ALGORITHM, TlsConfig.DEFAULT_DAYS);
    testHmac = TlsHelper.calculateHMac(testToken, caCertificate.getPublicKey());
    signedCsr = CertificateUtils.generateIssuedCertificate(
            jcaPKCS10CertificationRequest.getSubject().toString(), jcaPKCS10CertificationRequest.getPublicKey(),
            caCertificate, caKeyPair, TlsConfig.DEFAULT_SIGNING_ALGORITHM, TlsConfig.DEFAULT_DAYS);
    testSignedCsr = TlsHelper.pemEncodeJcaObject(signedCsr);

    tlsCertificateSigningRequestPerformer = new TlsCertificateSigningRequestPerformer(httpClientBuilderSupplier,
            tlsClientConfig);
}

From source file:eu.thecoder4.gpl.pleftdroid.PleftBroker.java

/**
 * @param desc//from   w w  w  .java 2 s  .  com
 * @param invitees
 * @param dates
 * @param pserver
 * @param uname
 * @param uemail
 */
static protected int createAppointment(String desc, String invitees, String dates, String pserver, String uname,
        String uemail, boolean proposemore) {
    int SC = SC_CLIREDIR;

    if (checkServer(pserver) == HttpStatus.SC_OK) {
        SC = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        HttpClient client = getDefaultClient();

        HttpPost request = new HttpPost(pserver + REQ_CREATE);
        List<NameValuePair> postParameters = new ArrayList<NameValuePair>(6);
        postParameters.add(new BasicNameValuePair("description", desc));
        postParameters.add(new BasicNameValuePair("name", uname));
        postParameters.add(new BasicNameValuePair("email", uemail));
        postParameters.add(new BasicNameValuePair("invitees", invitees));
        postParameters.add(new BasicNameValuePair("dates", dates));
        postParameters.add(new BasicNameValuePair("propose_more", (proposemore ? "1" : "0")));
        try {
            request.setEntity(new UrlEncodedFormEntity(postParameters));
            Log.i("PD d", desc);
            Log.i("PD d", uname);
            Log.i("PD d", uemail);
            Log.i("PD d", invitees);
            Log.i("PD d", dates);

            Log.i("PD", request.getURI().toString());
            Log.i("PD", request.getEntity().toString());
            HttpResponse response = client.execute(request);
            SC = response.getStatusLine().getStatusCode();
            Log.i("PD sc", " " + SC);

            response.getEntity().getContent().close(); //You need to open and close the IS to release the connection
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return SC;

}

From source file:org.apache.metamodel.neo4j.Neo4jRequestWrapperTest.java

@Test
public void testCreateCypherQueryWithoutAuthentication() {
    if (!isConfigured()) {
        System.err.println(getInvalidConfigurationMessage());
        return;//from   w w w . j  a v  a 2s . co  m
    }

    CloseableHttpClient mockHttpClient = new CloseableHttpClient() {

        @Override
        public void close() throws IOException {
            // Do nothing
        }

        @Override
        public HttpParams getParams() {
            // Do nothing
            return null;
        }

        @Override
        public ClientConnectionManager getConnectionManager() {
            // Do nothing
            return null;
        }

        @Override
        protected CloseableHttpResponse doExecute(HttpHost target, HttpRequest request, HttpContext context)
                throws IOException, ClientProtocolException {
            assertTrue(request instanceof HttpPost);
            HttpPost httpPost = (HttpPost) request;

            Header[] headers = httpPost.getHeaders("Authorization");
            assertNotNull(headers);
            assertEquals(0, headers.length);

            assertEquals("{\"statements\":[{\"statement\":\"MATCH (n) RETURN n;\"}]}",
                    EntityUtils.toString(httpPost.getEntity()));

            CloseableHttpResponse mockResponse = new MockClosableHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
            return mockResponse;
        }
    };

    Neo4jRequestWrapper wrapper = new Neo4jRequestWrapper(mockHttpClient,
            new HttpHost(getHostname(), getPort()), getServiceRoot());
    wrapper.executeCypherQuery("MATCH (n) RETURN n;");
    // Assertions are in the HttpClient
}

From source file:com.gsma.mobileconnect.impl.RequestTokenTest.java

@Test
public void requestToken_withDefaults_shouldCreateExpectedRequest()
        throws OIDCException, DiscoveryResponseExpiredException, IOException, RestException {
    // GIVEN/*w w  w  .j  ava  2  s .  com*/
    RestClient mockedRestClient = mock(RestClient.class);
    IOIDC ioidc = Factory.getOIDC(mockedRestClient);
    CaptureRequestTokenResponse captureRequestTokenResponse = new CaptureRequestTokenResponse();
    DiscoveryResponse discoveryResponse = new DiscoveryResponse(true, new Date(Long.MAX_VALUE), 0, null,
            parseJson(OPERATOR_JSON_STRING));

    final CaptureHttpRequestBase captureHttpRequestBase = new CaptureHttpRequestBase();
    final RestResponse restResponse = new RestResponse(null, 0, null, "{}");

    doAnswer(new Answer() {
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            Object[] args = invocationOnMock.getArguments();
            HttpRequestBase requestBase = (HttpRequestBase) args[0];
            captureHttpRequestBase.setValue(requestBase);
            return restResponse;
        }
    }).when(mockedRestClient).callRestEndPoint(any(HttpRequestBase.class), any(HttpClientContext.class),
            eq(30000), Matchers.<List<KeyValuePair>>any());

    // WHEN
    ioidc.requestToken(discoveryResponse, "", "", null, captureRequestTokenResponse);

    // THEN
    HttpRequestBase request = captureHttpRequestBase.getValue();

    assertEquals(TOKEN_HREF, request.getURI().toString());
    assertEquals("POST", request.getMethod());
    assertEquals("application/x-www-form-urlencoded", request.getFirstHeader("Content-Type").getValue());
    assertEquals("application/json", request.getFirstHeader("accept").getValue());

    assertTrue(request instanceof HttpPost);

    HttpPost postRequest = (HttpPost) request;
    List<NameValuePair> contents = URLEncodedUtils.parse(postRequest.getEntity());

    assertEquals("", findValueOfName(contents, "code"));
    assertEquals("authorization_code", findValueOfName(contents, "grant_type"));
    assertEquals("", findValueOfName(contents, "redirect_uri"));
}