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

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

Introduction

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

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:com.talis.labs.api.sparql11.http.Sparql11HttpRdfUpdateTest.java

private static void post(String graph, String mediaType, String lang)
        throws URISyntaxException, ClientProtocolException, IOException {
    StringWriter content = new StringWriter();
    model.write(content, lang);//from ww w .jav  a2  s  . c  o m

    StringEntity entity = new StringEntity(content.toString(), "UTF-8");

    URI uri = uri(graph);

    HttpPost httppost = new HttpPost(uri);
    httppost.setHeader("Content-Type", mediaType);
    httppost.setHeader("Accept", "text/plain");
    httppost.setEntity(entity);

    HttpResponse response = httpclient.execute(httppost);

    assertEquals(201, response.getStatusLine().getStatusCode());

    assertEquals(1, response.getHeaders("Location").length);
    assertEquals(EXISTING_GRAPH_URI, response.getFirstHeader("Location").getValue());

    response.getEntity().consumeContent();
}

From source file:org.opencastproject.remotetest.Main.java

private static void loadSeleneseData() throws Exception {
    System.out.println("Loading sample data for selenium HTML tests");
    // get the zipped mediapackage from the classpath
    byte[] bytesToPost = IOUtils.toByteArray(Main.class.getResourceAsStream("/ingest.zip"));

    // post it to the ingest service
    HttpPost post = new HttpPost(BASE_URL + "/ingest/addZippedMediaPackage");
    post.setEntity(new ByteArrayEntity(bytesToPost));
    TrustedHttpClient client = getClient();
    HttpResponse response = client.execute(post);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    String workflowXml = EntityUtils.toString(response.getEntity());

    // Poll the workflow service to ensure this recording processes successfully
    String workflowId = WorkflowUtils.getWorkflowInstanceId(workflowXml);
    while (true) {
        if (WorkflowUtils.isWorkflowInState(workflowId, "SUCCEEDED")) {
            SELENESE_DATA_LOADED = true;
            break;
        }/*www .  j  a  v  a 2 s . c om*/
        if (WorkflowUtils.isWorkflowInState(workflowId, "FAILED")) {
            Assert.fail("Unable to load sample data for selenese tests.");
        }
        Thread.sleep(5000);
        System.out.println("Waiting for sample data to process");
    }
    returnClient(client);
}

From source file:org.wso2.identity.integration.test.identity.governance.AdminForcedPasswordResetTestCase.java

private static HttpResponse sendPOSTMessage(String url, String userAgent, List<NameValuePair> urlParameters,
        HttpClient httpClient) throws Exception {
    HttpPost post = new HttpPost(url);
    post.setHeader("User-Agent", userAgent);
    post.setEntity(new UrlEncodedFormEntity(urlParameters));
    return httpClient.execute(post);
}

From source file:uk.ac.bbsrc.tgac.miso.integration.util.IntegrationUtils.java

public static String makePostRequest(String host, int port, String query) throws IntegrationException {
    if (query == null || query.isEmpty()) {
        throw new IntegrationException("Query must be populated when calling makePostRequest.");
    }/*from www.  j a v a2 s .  c  o  m*/

    String rtn = null;
    HttpClient httpclient = HttpClientBuilder.create().build();
    String url = "http://" + host + ":" + port + "/miso/";

    try {
        HttpPost httpPost = new HttpPost(url);
        // Request parameters and other properties.
        httpPost.setHeader("content-type", "application/x-www-form-urlencoded");
        System.out.println(query);
        httpPost.setEntity(new StringEntity(query));

        // Execute and get the response.
        HttpResponse response = httpclient.execute(httpPost);
        rtn = EntityUtils.toString(response.getEntity());
        if (rtn.charAt(0) == '"' && rtn.charAt(rtn.length() - 1) == '"') {
            System.out.println("Removing quotes");
            rtn = rtn.substring(1, rtn.length() - 1);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new IntegrationException("Cannot connect to " + url + " Cause: " + ex.getMessage());

    }
    return rtn;

}

From source file:com.amazonaws.eclipse.core.diagnostic.utils.AwsPortalFeedbackFormUtils.java

/**
 * Send the specified content by a POST request.
 *
 * @param httpClient// w  w w  . ja  v a 2  s. c om
 *            The http-client instance to use when sending the POST request.
 * @param payload
 *            The payload of the POST request.
 */
private static void sendFormPostRequest(final HttpClient httpClient, final String payload)
        throws AmazonClientException, AmazonServiceException {
    HttpPost request = new HttpPost(FORM_URL);

    request.addHeader("Content-Type", "application/x-www-form-urlencoded");

    try {
        request.setEntity(new StringEntity(payload, "UTF-8"));
    } catch (Exception e) {
        throw new AmazonClientException("Unable to send POST request to " + FORM_URL, e);
    }

    HttpResponse response;
    try {
        response = httpClient.execute(request);
    } catch (ClientProtocolException e) {
        throw new AmazonClientException("Unable to send POST request to " + FORM_URL, e);
    } catch (IOException e) {
        throw new AmazonClientException("Unable to send POST request to " + FORM_URL, e);
    }

    if (response.getStatusLine().getStatusCode() / 100 != HttpStatus.SC_OK / 100) {
        String responseContent;
        try {
            responseContent = IOUtils.toString(response.getEntity().getContent());
        } catch (IllegalStateException e) {
            throw new AmazonClientException("Unable to read POST response content.", e);
        } catch (IOException e) {
            throw new AmazonClientException("Unable to read POST response content.", e);
        }

        AmazonServiceException ase = new AmazonServiceException(
                "Unable to send POST request to " + FORM_URL + " : " + responseContent);
        ase.setStatusCode(response.getStatusLine().getStatusCode());

        throw ase;
    }
}

From source file:com.ilearnrw.reader.utils.HttpHelper.java

public static HttpResponse post(String url, String data) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = null;/*from  w  w w  . j av  a2s. co m*/

    //HttpConnectionParams.setSoTimeout(client.getParams(), 25000);

    HttpPost post = new HttpPost(url);
    post.setHeader("Accept", "application/json");
    post.setHeader("Authorization", "Basic " + authString);
    post.setHeader("Content-Type", "application/json;charset=utf-8");

    try {
        post.setEntity(new StringEntity(data, HTTP.UTF_8));
        response = client.execute(post);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    return response;
}

From source file:com.oakhole.voa.utils.HttpClientUtils.java

public static String post(String uri, File file) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(uri);
    try {// w  ww  . j  a  v a  2 s.c o m
        InputStreamEntity inputStreamEntity = new InputStreamEntity(new FileInputStream(file));
        //????
        httpPost.setEntity(inputStreamEntity);
        try {
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            httpResponse.close();
            return EntityUtils.toString(httpResponse.getEntity());
        } catch (IOException e) {
            logger.error(":{}", e.getMessage());
        }
    } catch (FileNotFoundException e) {
        logger.error(":{}", e.getMessage());
    }
    return "";
}

From source file:org.sahli.asciidoc.confluence.publisher.client.http.HttpRequestFactory.java

private static HttpPost addPageHttpPost(String confluenceRestApiEndpoint, PagePayload pagePayload) {
    String jsonPayload = toJsonString(pagePayload);
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(jsonPayload.getBytes()));

    HttpPost postRequest = new HttpPost(confluenceRestApiEndpoint + "/content");
    postRequest.setEntity(entity);
    postRequest.addHeader(APPLICATION_JSON_UTF8_HEADER);

    return postRequest;
}

From source file:utils.HttpComm.java

public static String schedulerPost(String workerURL, Map<String, String> postArguments) throws Exception {
    HttpPost httpPost = new HttpPost(workerURL);
    httpPost.setProtocolVersion(HttpVersion.HTTP_1_1);
    List<NameValuePair> nvps = new ArrayList<>();
    for (String key : postArguments.keySet())
        nvps.add(new BasicNameValuePair(key, postArguments.get(key)));

    httpPost.setEntity(new UrlEncodedFormEntity(nvps));

    try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
        //System.out.println(response.getStatusLine());
        HttpEntity entity = response.getEntity();
        String s = EntityUtils.toString(entity);
        EntityUtils.consume(entity);//from   w  w w  .j  av a 2 s  .  c o m
        return s;
    } finally {
        httpPost.releaseConnection();
    }
}

From source file:utils.ImportExportUtils.java

/**
 * Registering the clientApplication/*w  ww .ja  v a  2 s  .  c o  m*/
 * @param username user name of the client
 * @param password password of the client
 */
static String registerClient(String username, String password) throws APIExportException {

    ApiImportExportConfiguration config = ApiImportExportConfiguration.getInstance();

    String concatUsernamePassword = username + ":" + password;
    byte[] encodedBytes = Base64
            .encodeBase64(concatUsernamePassword.getBytes(Charset.forName(ImportExportConstants.CHARSET)));
    String encodedCredentials;
    try {
        encodedCredentials = new String(encodedBytes, ImportExportConstants.CHARSET);
    } catch (UnsupportedEncodingException e) {
        String error = "Error occurred while encoding the user credentials";
        log.error(error, e);
        throw new APIExportException(error, e);
    }
    //payload for registering
    JSONObject jsonObject = new JSONObject();
    jsonObject.put(ImportExportConstants.CLIENT_NAME, config.getClientName());
    jsonObject.put(ImportExportConstants.OWNER, username);
    jsonObject.put(ImportExportConstants.GRANT_TYPE, ImportExportConstants.DEFAULT_GRANT_TYPE);
    jsonObject.put(ImportExportConstants.SAAS_APP, true);

    //REST API call for registering
    CloseableHttpResponse response;
    String encodedConsumerDetails;
    CloseableHttpClient client = null;
    try {
        String url = config.getDcrUrl();
        client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
        HttpPost request = new HttpPost(url);
        request.setEntity(new StringEntity(jsonObject.toJSONString(), ImportExportConstants.CHARSET));
        request.setHeader(HttpHeaders.AUTHORIZATION,
                ImportExportConstants.AUTHORIZATION_KEY_SEGMENT + " " + encodedCredentials);
        request.setHeader(HttpHeaders.CONTENT_TYPE, ImportExportConstants.CONTENT_JSON);
        response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 401) {
            String errormsg = "invalid username or password entered ";
            log.error(errormsg);
            throw new APIExportException(errormsg);
        }
        String jsonString = EntityUtils.toString(response.getEntity());
        JSONObject jsonObj = (JSONObject) new JSONParser().parse(jsonString);

        //storing encoded Consumer credentials
        String consumerCredentials = jsonObj.get(ImportExportConstants.CLIENT_ID) + ":"
                + jsonObj.get(ImportExportConstants.CLIENT_SECRET);
        byte[] bytes = Base64.encodeBase64(consumerCredentials.getBytes(Charset.defaultCharset()));
        encodedConsumerDetails = new String(bytes, ImportExportConstants.CHARSET);
    } catch (ParseException e) {
        String msg = "error occurred while getting consumer key and consumer secret from the response";
        log.error(msg, e);
        throw new APIExportException(msg, e);
    } catch (IOException e) {
        String msg = "Error occurred while registering the client";
        log.error(msg, e);
        throw new APIExportException(msg, e);
    } finally {
        IOUtils.closeQuietly(client);
    }
    return encodedConsumerDetails;
}