Example usage for org.apache.http.client.entity EntityBuilder create

List of usage examples for org.apache.http.client.entity EntityBuilder create

Introduction

In this page you can find the example usage for org.apache.http.client.entity EntityBuilder create.

Prototype

public static EntityBuilder create() 

Source Link

Usage

From source file:RGSOplataRu.OplataConnection.java

@Override
public String POST_Request(String p_uri, Object... p_objects) throws IOException {
    String result = "";
    HttpPost request = new HttpPost(p_uri);
    request = getRequestConfigurator().Configurate(request);

    if (p_objects.length > 0) {
        HttpEntity reqEntity = EntityBuilder.create().setText((String) p_objects[0])
                .setContentType(ContentType.create(request.getFirstHeader("Content-Type").getValue(),
                        Charset.forName(request.getFirstHeader("charset").getValue())))
                .build();/*w ww  .  j  a v a 2  s .  c o m*/

        request.setEntity(reqEntity);
        //            System.out.println("target= "+target);
        //            System.out.println("httpClient= "+httpClient);
        //            System.out.println("request= "+request.getFirstHeader("charset").getValue());
        //            System.out.println("request= "+request.getFirstHeader("Content-Type").getValue());
        //            System.out.println("request entity= " + request.getEntity());

        //            System.out.println("request headers:");
        //            for( Header h : request.getAllHeaders()){
        //                
        //                System.out.println(h.getName() + ":" + h.getValue());
        //            }
        CloseableHttpResponse responce = httpClient.execute(target, request);
        result = responceToString(responce);
    }

    return result;
}

From source file:org.sakaiproject.contentreview.urkund.util.UrkundAPIUtil.java

public static String postDocument(String baseUrl, String receiverAddress, String externalId,
        UrkundSubmission submission, String urkundUsername, String urkundPassword, int timeout) {
    String ret = null;/*from   w ww.  ja va 2s.  com*/

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(timeout);
    requestBuilder = requestBuilder.setConnectionRequestTimeout(timeout);

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestBuilder.build());
    try (CloseableHttpClient httpClient = builder.build()) {

        HttpPost httppost = new HttpPost(baseUrl + "submissions/" + receiverAddress + "/" + externalId);
        //------------------------------------------------------------
        EntityBuilder eBuilder = EntityBuilder.create();
        eBuilder.setBinary(submission.getContent());

        httppost.setEntity(eBuilder.build());
        //------------------------------------------------------------
        if (StringUtils.isNotBlank(urkundUsername) && StringUtils.isNotBlank(urkundPassword)) {
            addAuthorization(httppost, urkundUsername, urkundPassword);
        }
        //------------------------------------------------------------
        httppost.addHeader("Accept", "application/json");
        httppost.addHeader("Content-Type", submission.getMimeType());
        httppost.addHeader("Accept-Language", submission.getLanguage());
        httppost.addHeader("x-urkund-filename", submission.getFilenameEncoded());
        httppost.addHeader("x-urkund-submitter", submission.getSubmitterEmail());
        httppost.addHeader("x-urkund-anonymous", Boolean.toString(submission.isAnon()));
        httppost.addHeader("x-urkund-subject", submission.getSubject());
        httppost.addHeader("x-urkund-message", submission.getMessage());
        //------------------------------------------------------------

        HttpResponse response = httpClient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {
            ret = EntityUtils.toString(resEntity);
            EntityUtils.consume(resEntity);
        }

    } catch (IOException e) {
        log.error("ERROR uploading File : ", e);
    }

    return ret;
}

From source file:org.opendaylight.alto.manager.AltoDeleteTest.java

@Test
public void testDoExecute() throws Exception {
    HttpResponse response = mock(HttpResponse.class);
    HttpEntity entity = EntityBuilder.create().setText(DEFAULT_NETWORK_MAP).build();
    StatusLine statusLine = mock(StatusLine.class);
    doReturn(response).when(httpClient).execute(any(HttpDelete.class));
    doReturn(statusLine).when(response).getStatusLine();
    doReturn(200).when(statusLine).getStatusCode();
    doReturn(response).when(altoDelete).httpGet(AltoManagerConstants.IRD_DEFAULT_NETWORK_MAP_URL);
    doReturn(entity).when(response).getEntity();

    altoDelete.resourceType = "network-map";
    altoDelete.resourceId = "my-default-network-map";
    altoDelete.doExecute();//from ww w .  ja va 2s  .  co m
    verify(httpClient, atLeastOnce()).execute(any(HttpDelete.class));
    altoDelete.resourceType = "cost-map";
    altoDelete.resourceId = "my-default-network-map-routingcost-numerical";
    altoDelete.doExecute();
    verify(httpClient, atLeastOnce()).execute(any(HttpDelete.class));
    altoDelete.resourceType = "endpoint-property-map";
    altoDelete.resourceId = null;
    altoDelete.doExecute();
    verify(httpClient, atLeastOnce()).execute(any(HttpDelete.class));
    altoDelete.resourceType = "otherwise";
    altoDelete.resourceId = "";
    try {
        altoDelete.doExecute();
    } catch (Exception e) {
        Assert.assertEquals(e.getClass(), UnsupportedOperationException.class);
    }
}

From source file:com.jkoolcloud.tnt4j.streams.fields.ActivityCacheTest.java

private static void sendRequest(HttpClient client, String file) throws Exception {
    URI url = makeURI();/*  w  w w .j a v  a 2 s  .co  m*/
    HttpPost post = new HttpPost(url);

    post.setEntity(EntityBuilder.create().setText(getFileContents(file)).build());
    final HttpResponse returned = client.execute(post);
}

From source file:com.smartling.cms.gateway.client.upload.FileUpload.java

protected EntityBuilder getEntityBuilder() throws IOException {
    return EntityBuilder.create().setContentType(contentType).chunked().setStream(contentStream);
}

From source file:com.smartling.cms.gateway.client.upload.HtmlUpload.java

@Override
protected EntityBuilder getEntityBuilder() throws IOException {
    JsonObject response = new JsonObject();
    response.addProperty("baseUrl", baseUrl);
    response.addProperty("body", IOUtils.toString(getInputStream()));

    if (StringUtils.isNotEmpty(publicUrl))
        response.addProperty("publicUrl", publicUrl);

    return EntityBuilder.create().setContentType(ContentType.APPLICATION_JSON).setText(response.toString());
}

From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java

/**
 * Executes the authentication to the Jaspersoft community in order to
 * retrieve the session cookie to use later for all other operations.
 * /*from   www . j  a va  2s . c om*/
 * @param httpclient
 *            the http client
 * 
 * @param cookieStore
 *            the Cookie Store instance
 * @param username
 *            the community user name (or email)
 * @param password
 *            the community user password
 * @return the authentication cookie if able to retrieve it,
 *         <code>null</code> otherwise
 * @throws CommunityAPIException
 */
public static Cookie getAuthenticationCookie(CloseableHttpClient httpclient, CookieStore cookieStore,
        String username, String password) throws CommunityAPIException {

    try {
        HttpPost loginPOST = new HttpPost(CommunityConstants.LOGIN_URL);
        EntityBuilder loginEntity = EntityBuilder.create();
        loginEntity.setText("{ \"username\": \"" + username + "\", \"password\":\"" + password + "\" }"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        loginEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE));
        loginEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET);
        loginPOST.setEntity(loginEntity.build());

        CloseableHttpResponse resp = httpclient.execute(loginPOST);
        int httpRetCode = resp.getStatusLine().getStatusCode();
        String responseBodyAsString = EntityUtils.toString(resp.getEntity());
        if (HttpStatus.SC_OK == httpRetCode) {
            // Can proceed
            List<Cookie> cookies = cookieStore.getCookies();
            Cookie authCookie = null;
            for (Cookie cookie : cookies) {
                if (cookie.getName().startsWith("SESS")) { //$NON-NLS-1$
                    authCookie = cookie;
                    break;
                }
            }
            return authCookie;
        } else if (HttpStatus.SC_UNAUTHORIZED == httpRetCode) {
            // Unauthorized... wrong username or password
            CommunityAPIException unauthorizedEx = new CommunityAPIException(
                    Messages.RESTCommunityHelper_WrongUsernamePasswordError);
            unauthorizedEx.setHttpStatusCode(httpRetCode);
            unauthorizedEx.setResponseBodyAsString(responseBodyAsString);
            throw unauthorizedEx;
        } else {
            // Some other problem occurred
            CommunityAPIException generalEx = new CommunityAPIException(
                    Messages.RESTCommunityHelper_AuthInfoProblemsError);
            generalEx.setHttpStatusCode(httpRetCode);
            generalEx.setResponseBodyAsString(responseBodyAsString);
            throw generalEx;
        }
    } catch (UnsupportedEncodingException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_AuthenticationError, e);
    } catch (IOException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_AuthenticationError, e);
    }
}

From source file:com.nextdoor.bender.ipc.http.HttpTransportTest.java

private HttpClient getMockClientWithResponse(byte[] respPayload, ContentType contentType, int status,
        boolean compressed) throws IOException {
    HttpClient mockClient = mock(HttpClient.class);
    HttpResponse mockResponse = mock(HttpResponse.class);

    StatusLine mockStatusLine = mock(StatusLine.class);
    doReturn("expected failure").when(mockStatusLine).getReasonPhrase();
    doReturn(status).when(mockStatusLine).getStatusCode();
    doReturn(mockStatusLine).when(mockResponse).getStatusLine();
    EntityBuilder eb = EntityBuilder.create().setBinary(respPayload).setContentType(contentType);

    HttpEntity he;/*w w  w  .  j  a v a2 s  .c om*/
    if (compressed) {
        eb.setContentEncoding("gzip");
        he = new GzipDecompressingEntity(eb.build());
    } else {
        he = eb.build();
    }

    doReturn(he).when(mockResponse).getEntity();

    doReturn(mockResponse).when(mockClient).execute(any(HttpPost.class));
    return mockClient;
}

From source file:cpcc.com.services.CommunicationServiceImpl.java

/**
 * {@inheritDoc}/*from   w  w  w .  j  ava2 s  .co  m*/
 */
@Override
public CommunicationResponse transfer(RealVehicle realVehicle, String connector, byte[] data)
        throws ClientProtocolException, IOException {
    HttpPost request = new HttpPost(realVehicle.getUrl() + connectorMap.get(connector));

    HttpEntity entity = EntityBuilder.create().setBinary(data).build();
    request.setEntity(entity);

    try (CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = httpclient.execute(request)) {
        HttpEntity responseEntity = response.getEntity();
        InputStream ins = responseEntity.getContent();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(ins, baos);
        byte[] content = baos.toByteArray();

        boolean ok = response.getStatusLine().getStatusCode() == 200;

        CommunicationResponse r = new CommunicationResponse();
        r.setStatus(ok ? Status.OK : Status.NOT_OK);
        r.setContent(content);
        return r;
    }
}

From source file:RGSOplataRu.OplataConnection.java

public Clob POST_RequestDBClob(String p_uri, Object... p_objects) throws IOException, SQLException {
    Clob result = null;// ww  w  . j av a  2 s  .c  o m
    HttpPost request = new HttpPost(p_uri);
    request = getRequestConfigurator().Configurate(request);

    if (p_objects.length > 0) {

        HttpEntity reqEntity = EntityBuilder.create().setText((String) p_objects[0])
                //.setContentType(ContentType.create("text/plain", Charset.forName("utf-8")))
                .build();

        request.setEntity(reqEntity);
        //            System.out.println("target: "+target);
        //            System.out.println("httpClient: "+httpClient);
        //            System.out.println("request: "+request);
        CloseableHttpResponse responce = httpClient.execute(target, request);
        result = Stream2Clob(responce.getEntity().getContent());
    }

    return result;
}