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:org.nuxeo.connect.registration.RegistrationHelper.java

/**
 * @since 1.4.25//from w w w  . j  a va  2s  .  c  o m
 */
public static TrialRegistrationResponse remoteTrialInstanceRegistration(Map<String, String> parameters) {
    String url = getTrialRegistrationBaseUrl() + "submit?embedded=true";
    List<NameValuePair> nvps = new ArrayList<>();
    for (Map.Entry<String, String> entry : parameters.entrySet()) {
        if (!ALLOWED_TRIAL_FIELDS.contains(entry.getKey())) {
            log.debug("Skipped field: " + entry.getKey() + " (" + entry.getValue() + ")");
            continue;
        }
        nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }
    HttpPost method = new HttpPost(url);
    try {
        method.setEntity(new UrlEncodedFormEntity(nvps));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    try (CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse httpResponse = httpClient.execute(method,
                    getHttpClientContext(url, null, null))) {
        int rc = httpResponse.getStatusLine().getStatusCode();
        log.debug("Registration response code: " + rc);
        HttpEntity responseEntity = httpResponse.getEntity();
        if (responseEntity != null) {
            String body = EntityUtils.toString(responseEntity);
            if (rc == HttpStatus.SC_OK) {
                return TrialRegistrationResponse.read(body);
            } else if (rc == HttpStatus.SC_BAD_REQUEST) {
                return TrialRegistrationResponse.read(body);
            } else {
                log.error("Unhandled response code: " + rc);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return TrialErrorResponse.UNKNOWN();
}

From source file:com.seleniumtests.browserfactory.SauceLabsDriverFactory.java

/**
 * Upload application to saucelabs server
 * @param targetAppPath/* www .ja v a2s. co  m*/
 * @param serverURL
 * @return
 * @throws IOException
 * @throws AuthenticationException 
 */
protected static boolean uploadFile(String targetAppPath) throws IOException, AuthenticationException {

    // extract user name and password from getWebDriverGrid
    Matcher matcher = REG_USER_PASSWORD
            .matcher(SeleniumTestsContextManager.getThreadContext().getWebDriverGrid().get(0));
    String user;
    String password;
    if (matcher.matches()) {
        user = matcher.group(1);
        password = matcher.group(2);
    } else {
        throw new ConfigurationException(
                "getWebDriverGrid variable does not have the right format for connecting to sauceLabs");
    }

    FileEntity entity = new FileEntity(new File(targetAppPath));
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);

    HttpPost request = new HttpPost(String.format(SAUCE_UPLOAD_URL, user, new File(targetAppPath).getName()));
    request.setEntity(entity);
    request.addHeader(new BasicScheme().authenticate(creds, request, null));
    request.addHeader("Content-Type", "application/octet-stream");

    try (CloseableHttpClient client = HttpClients.createDefault();) {
        CloseableHttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() != 200) {
            client.close();
            throw new ConfigurationException(
                    "Application file upload failed: " + response.getStatusLine().getReasonPhrase());
        }
    }

    return true;
}

From source file:org.opencastproject.remotetest.server.resource.SchedulerResources.java

public static HttpResponse findConflictingEvents(TrustedHttpClient client, String event) throws Exception {
    HttpPost post = new HttpPost(getServiceUrl() + "findConflictingEvents");
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("event", event));
    post.setEntity(new UrlEncodedFormEntity(params));
    return client.execute(post);
}

From source file:Technique.PostFile.java

public static void upload(String files) throws Exception {

    String userHome = System.getProperty("user.home");
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost("http://localhost/image/up.php");
    File file = new File(files);
    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody contentFile = new FileBody(file);
    mpEntity.addPart("userfile", contentFile);
    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    if (!(response.getStatusLine().toString()).equals("HTTP/1.1 200 OK")) {
        // Successfully Uploaded
    } else {/*from w w  w  . j  ava  2  s.  c  o  m*/
        // Did not upload. Add your logic here. Maybe you want to retry.
    }
    System.out.println(response.getStatusLine());
    if (resEntity != null) {
        System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
        resEntity.consumeContent();
    }
    httpclient.getConnectionManager().shutdown();
}

From source file:org.dbrane.cloud.util.httpclient.HttpClientHelper.java

public static String httpPostRequest(String url, Map<String, Object> params) {
    try {/*from w w  w  .j  a  va  2s .com*/
        HttpPost httpPost = new HttpPost(url);
        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
        return getResult(httpPost);
    } catch (Exception e) {
        logger.debug(ErrorType.Httpclient.toString(), e);
        throw new BaseException(ErrorType.Httpclient, e);
    }
}

From source file:coolmapplugin.util.HTTPRequestUtil.java

public static String executePost(String targetURL, String jsonBody) {

    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

        HttpPost request = new HttpPost(targetURL);

        StringEntity params = new StringEntity(jsonBody);
        request.addHeader("content-type", "application/json");
        request.setEntity(params);

        HttpResponse result = httpClient.execute(request);

        HttpEntity entity = result.getEntity();
        if (entity == null)
            return null;

        String jsonResult = EntityUtils.toString(result.getEntity(), "UTF-8");

        return jsonResult;

    } catch (IOException e) {
        return null;
    }//ww w  .  j a va2 s  .c  o m
}

From source file:httpServerClient.app.QuickStart.java

public static void sendMessage(String[] args) throws Exception {
    // arguments to run Quick start POST:
    // args[0] POST
    // args[1] IPAddress of server
    // args[2] port No.
    // args[3] user name
    // args[4] myMessage
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {//  www .j av a 2s.c  o  m
        HttpPost httpPost = new HttpPost("http://" + args[1] + ":" + args[2] + "/sendMessage");
        // httpPost.setEntity(new StringEntity("lubo je kral"));
        httpPost.setEntity(
                new StringEntity("{\"name\":\"" + args[3] + "\",\"myMessage\":\"" + args[4] + "\"}"));
        CloseableHttpResponse response1 = httpclient.execute(httpPost);
        // The underlying HTTP connection is still held by the response
        // object
        // to allow the response content to be streamed directly from the
        // network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally
        // clause.
        // Please note that if response content is not fully consumed the
        // underlying
        // connection cannot be safely re-used and will be shut down and
        // discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();

            /*
             * Vypisanie odpovede do konzoly a discard dat zo serveru.
             */

            System.out.println(EntityUtils.toString(entity1));
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

    } finally {
        httpclient.close();
    }
}

From source file:net.bioclipse.dbxp.business.DbxpManager.java

public static HttpResponse postValues(HashMap<String, String> postvars, String url)
        throws NoSuchAlgorithmException, ClientProtocolException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(userName, password));

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    Iterator<Entry<String, String>> it = postvars.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> next = (Map.Entry<String, String>) it.next();
        Map.Entry<String, String> pairs = next;
        formparams.add(new BasicNameValuePair(pairs.getKey(), pairs.getValue()));
    }/*from   w w  w .j  a v  a2  s .c o m*/
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(entity);
    HttpContext localContext = new BasicHttpContext();
    return httpclient.execute(httppost, localContext);
}

From source file:com.jts.main.helper.Http.java

public static String getPost(String url, URLParameter param) {
    String retval = "";
    HttpClient httpClient = new DefaultHttpClient();
    try {//from   w ww  .  ja v a2  s .c o  m
        String prm = param.toString();
        HttpPost request = new HttpPost(My.base_url + url);
        StringEntity params = new StringEntity(prm);
        request.addHeader("content-type", "application/x-www-form-urlencoded");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
        // handle response here...
        retval = org.apache.http.util.EntityUtils.toString(response.getEntity());
        org.apache.http.util.EntityUtils.consume(response.getEntity());
    } catch (IOException | ParseException ex) {
        errMsg = ex.getMessage();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return retval;
}

From source file:org.androidnerds.reader.util.api.Authentication.java

/**
 * This method returns back to the caller a proper authentication token to use with
 * the other API calls to Google Reader.
 *
 * @param user - the Google username//from w  w  w.  j av  a  2 s .  com
 * @param pass - the Google password
 * @return sid - the returned authentication token for use with the API.
 *
 */
public static String getAuthToken(String user, String pass) {
    NameValuePair username = new BasicNameValuePair("Email", user);
    NameValuePair password = new BasicNameValuePair("Passwd", pass);
    NameValuePair service = new BasicNameValuePair("service", "reader");
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(username);
    pairs.add(password);
    pairs.add(service);

    try {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(AUTH_URL);
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs);

        post.setEntity(entity);

        HttpResponse response = client.execute(post);
        HttpEntity respEntity = response.getEntity();

        Log.d(TAG, "Server Response: " + response.getStatusLine());

        InputStream in = respEntity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        String result = null;

        while ((line = reader.readLine()) != null) {
            if (line.startsWith("SID")) {
                result = line.substring(line.indexOf("=") + 1);
            }
        }

        reader.close();
        client.getConnectionManager().shutdown();

        return result;
    } catch (Exception e) {
        Log.d(TAG, "Exception caught:: " + e.toString());
        return null;
    }
}