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.navnorth.learningregistry.LRClient.java

public static String executeHttpPost(String url, ArrayList postParameters) throws Exception {
    BufferedReader in = null;//w  ww.  ja  va 2s .com

    try {
        URI uri = new URI(url);
        HttpClient client = getHttpClient(uri.getScheme());
        HttpPost request = new HttpPost(uri);

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
        request.setEntity(formEntity);
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();
        String result = sb.toString();
        return result;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:att.jaxrs.client.Library.java

public static String updateLibrary(Library library) {

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("category_id", Integer.toString(library.getCategory_id())));
    urlParameters.add(new BasicNameValuePair("title", library.getTitle()));
    urlParameters.add(new BasicNameValuePair("published_date", library.getPublished_date()));
    urlParameters.add(new BasicNameValuePair("url", library.getUrl()));

    String resultStr = "";

    try {//from  ww  w.j a v a  2  s. co  m

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(Constants.UPDATE_LIBRARY_RESOURCE);
        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        HttpResponse result = httpClient.execute(post);
        System.out.println(Constants.RESPONSE_STATUS_CODE + result);
        resultStr = Util.getStringFromInputStream(result);
        System.out.println(Constants.RESPONSE_BODY + resultStr);
        System.out.println("testing $$$$$$$$$$$$$$$$$$$$$$");
    } catch (Exception e) {
        System.out.println(e.getMessage());

    }
    return resultStr;
}

From source file:co.aurasphere.botmill.telegram.internal.util.network.NetworkUtils.java

/**
 * POSTs a message as a JSON string to Telegram.
 * //w  w  w. j  a  v  a2  s.  c o  m
 * @param input
 *            the JSON data to send.
 * @param method
 *            the Telegram method to call.
 */
public static void postJsonMessage(StringEntity input, TelegramMethod method) {
    String botToken = TelegramBotMillContext.getInstance().getBotToken();
    // If the page token is invalid, returns.

    HttpPost post = new HttpPost(BASE_TELEGRAM_ENDPOINT + botToken + "/" + method.getMethodName());
    post.setEntity(input);
    send(post);
}

From source file:com.networknt.light.server.handler.loader.Loader.java

public static void login(String host, String userId, String password) throws Exception {
    Map<String, Object> inputMap = new HashMap<String, Object>();
    inputMap.put("category", "user");
    inputMap.put("name", "signInUser");
    inputMap.put("readOnly", false);
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("userIdEmail", userId);
    data.put("password", password);
    data.put("rememberMe", true);
    data.put("clientId", "example@Browser");
    inputMap.put("data", data);

    HttpPost httpPost = new HttpPost(host + "/api/rs");
    StringEntity input = new StringEntity(
            ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap));
    input.setContentType("application/json");
    httpPost.setEntity(input);
    CloseableHttpResponse response = httpclient.execute(httpPost);

    try {/*from   w w  w .j av  a2  s.c  o  m*/

        //System.out.println(response.getStatusLine());
        HttpEntity entity = response.getEntity();
        BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
        String json = "";
        String line = "";
        while ((line = rd.readLine()) != null) {
            json = json + line;
        }
        //System.out.println("json = " + json);
        Map<String, Object> jsonMap = ServiceLocator.getInstance().getMapper().readValue(json,
                new TypeReference<HashMap<String, Object>>() {
                });
        jwt = (String) jsonMap.get("accessToken");
        EntityUtils.consume(entity);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        response.close();
    }
}

From source file:de.hybris.platform.integration.cis.payment.strategies.impl.CisPaymentIntegrationTestHelper.java

public static Map<String, String> createNewProfile(final String cybersourceUrl,
        final List<BasicNameValuePair> formData) throws Exception // NO PMD
{
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpPost postRequest = new HttpPost(cybersourceUrl);
    postRequest.getParams().setBooleanParameter("http.protocol.handle-redirects", true);
    postRequest.setEntity(new UrlEncodedFormEntity(formData, "UTF-8"));
    // Execute HTTP Post Request
    final HttpResponse response = client.execute(postRequest);
    final Map<String, String> responseParams = new HashMap<String, String>();
    BufferedReader bufferedReader = null;
    try {//from  w  ww. ja  v a2  s . co  m
        bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

        while (bufferedReader.ready()) {
            final String currentLine = bufferedReader.readLine();
            if (currentLine.contains("value=\"") && currentLine.contains("name=\"")) {
                final String[] splittedLine = currentLine.split("name=\"");
                final String key = splittedLine[1].split("value=\"")[0].replace("\"", "").replace(">", "")
                        .trim();
                final String value = splittedLine[1].split("value=\"")[1].replace("\"", "").replace(">", "")
                        .trim();
                responseParams.put(key, value);
            }
        }
    } finally {
        IOUtils.closeQuietly(bufferedReader);
    }

    return responseParams;
}

From source file:com.photon.phresco.nativeapp.eshop.net.HttpRequest.java

/**
 * Send the JSON data to specified URL and get the httpResponse back
 *
 * @param sURL/*  ww  w  . j a  va2s . c om*/
 * @param jObject
 * @return InputStream
 * @throws IOException
 */
public static InputStream post(String sURL, JSONObject jObject) throws IOException {
    HttpResponse httpResponse = null;
    InputStream is = null;

    PhrescoLogger.info(TAG + " post: " + sURL);
    PhrescoLogger.info(TAG + " jObject: " + jObject);

    HttpPost httpPostRequest = new HttpPost(sURL);
    HttpEntity entity;

    httpPostRequest.setHeader("Accept", "application/json");
    httpPostRequest.setHeader(HTTP.CONTENT_TYPE, "application/json");
    httpPostRequest.setEntity(new ByteArrayEntity(jObject.toString().getBytes("UTF-8")));
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    int timeoutConnection = TIME_OUT;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = TIME_OUT;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    httpResponse = httpClient.execute(httpPostRequest);

    if (httpResponse != null) {
        entity = httpResponse.getEntity();
        is = entity.getContent();
    }
    return is;
}

From source file:att.jaxrs.client.Library.java

public static String addLibrary(Library library) {

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("category_id", Integer.toString(library.getCategory_id())));
    urlParameters.add(new BasicNameValuePair("title", library.getTitle()));
    urlParameters.add(new BasicNameValuePair("published_date", library.getPublished_date()));
    urlParameters.add(new BasicNameValuePair("url", library.getUrl()));

    HttpResponse result;//w  w w  .  j  av a2s  .co  m
    String resultStr = "";

    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(Constants.INSERT_LIBRARY_RESOURCE);
        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        result = httpClient.execute(post);
        System.out.println(Constants.RESPONSE_STATUS_CODE + result);
        resultStr = Util.getStringFromInputStream(result.getEntity().getContent());
        System.out.println(Constants.RESPONSE_BODY + resultStr);

    } catch (Exception e) {
        System.out.println(e.getMessage());

    }
    return resultStr;
}

From source file:com.linecorp.armeria.server.ServerTest.java

private static void testInvocation0(String path) throws IOException {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        final HttpPost req = new HttpPost(uri(path));
        req.setEntity(new StringEntity("Hello, world!", StandardCharsets.UTF_8));

        try (CloseableHttpResponse res = hc.execute(req)) {
            assertThat(res.getStatusLine().toString(), is("HTTP/1.1 200 OK"));
            assertThat(EntityUtils.toString(res.getEntity()), is("Hello, world!"));
        }//www .j ava2  s.  com
    }
}

From source file:com.predic8.membrane.test.AssertUtils.java

public static String postAndAssert(int expectedHttpStatusCode, String url, String[] headers, String body)
        throws ClientProtocolException, IOException {
    if (hc == null)
        hc = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    for (int i = 0; i < headers.length; i += 2)
        post.setHeader(headers[i], headers[i + 1]);
    post.setEntity(new StringEntity(body));
    try {//from w  ww . j a  v a2s. c o  m
        HttpResponse res = hc.execute(post);
        assertEquals(expectedHttpStatusCode, res.getStatusLine().getStatusCode());
        return EntityUtils.toString(res.getEntity());
    } finally {
        post.releaseConnection();
    }
}

From source file:io.fabric8.maven.support.Apps.java

/**
 * Posts a file to the git repository/*from w  w w  . j  a va 2  s.c o  m*/
 */
public static HttpResponse postFileToGit(File file, String user, String password, String consoleUrl,
        String branch, String path, Logger logger) throws URISyntaxException, IOException {
    HttpClientBuilder builder = HttpClients.custom();
    if (Strings.isNotBlank(user) && Strings.isNotBlank(password)) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", 443),
                new UsernamePasswordCredentials(user, password));
        builder = builder.setDefaultCredentialsProvider(credsProvider);
    }

    CloseableHttpClient client = builder.build();
    try {

        String url = consoleUrl;
        if (!url.endsWith("/")) {
            url += "/";
        }
        url += "git/";
        url += branch;
        if (!path.startsWith("/")) {
            url += "/";
        }
        url += path;

        logger.info("Posting App Zip " + file.getName() + " to " + url);
        URI buildUrl = new URI(url);
        HttpPost post = new HttpPost(buildUrl);

        // use multi part entity format
        FileBody zip = new FileBody(file);
        HttpEntity entity = MultipartEntityBuilder.create().addPart(file.getName(), zip).build();
        post.setEntity(entity);
        // post.setEntity(new FileEntity(file));

        HttpResponse response = client.execute(URIUtils.extractHost(buildUrl), post);
        logger.info("Response: " + response);
        if (response != null) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode < 200 || statusCode >= 300) {
                throw new IllegalStateException("Failed to post App Zip to: " + url + " " + response);
            }
        }
        return response;
    } finally {
        Closeables.closeQuietly(client);
    }
}