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:communication.Communicator.java

/**
 * Adds a new trackingPosition to an existing cartracker
 *
 * @param tracker The cartracker with a new trackingPosition
 * @return The serialnumber of the new trackingPosition
 * @throws IOException/*from   w w  w  . ja v a2  s.c  o  m*/
 */
public static Long postTrackingPositionsForTracker(CarTracker tracker) throws IOException {
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(BASE_URL_PRODUCTION + "/" + tracker.getId() + "/movements");
    String jsonBody = gson.toJson(tracker.getCurrentTrackingPeriod());
    StringEntity postingString = new StringEntity(jsonBody, CHARACTER_SET);
    post.setEntity(postingString);
    post.setHeader(HTTP.CONTENT_TYPE, "application/json");
    HttpResponse response = httpClient.execute(post);

    String responseString = EntityUtils.toString(response.getEntity(), CHARACTER_SET);
    JSONObject json = new JSONObject(responseString);
    return json.getLong("serialNumber");
}

From source file:org.fdroid.enigtext.mms.MmsSendHelper.java

private static byte[] makePost(Context context, MmsConnectionParameters parameters, byte[] mms)
        throws ClientProtocolException, IOException {
    AndroidHttpClient client = null;//from  ww  w  .  j  av a  2  s  .c o m

    try {
        Log.w("MmsSender", "Sending MMS1 of length: " + (mms != null ? mms.length : "null"));
        client = constructHttpClient(context, parameters);
        URI targetUrl = new URI(parameters.getMmsc());

        if (Util.isEmpty(targetUrl.getHost()))
            throw new IOException("Invalid target host: " + targetUrl.getHost() + " , " + targetUrl);

        HttpHost target = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
        HttpPost request = new HttpPost(parameters.getMmsc());
        ByteArrayEntity entity = new ByteArrayEntity(mms);

        entity.setContentType("application/vnd.wap.mms-message");

        request.setEntity(entity);
        request.setParams(client.getParams());
        request.addHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic");
        request.addHeader("x-wap-profile", "http://www.google.com/oha/rdf/ua-profile-kila.xml");
        HttpResponse response = client.execute(target, request);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() != 200)
            throw new IOException("Non-successful HTTP response: " + status.getReasonPhrase());

        return parseResponse(response.getEntity());
    } catch (URISyntaxException use) {
        Log.w("MmsSendHelper", use);
        throw new IOException("Couldn't parse URI.");
    } finally {
        if (client != null)
            client.close();
    }
}

From source file:cn.mrdear.pay.util.WebUtils.java

/**
 * POST/*  www  . j  a v  a2s  .  c  o  m*/
 * 
 * @param url
 *            URL
 * @param parameterMap
 *            ?
 * @return 
 */
public static String post(String url, Map<String, Object> parameterMap) {

    String result = null;
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        if (parameterMap != null) {
            for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {
                String name = entry.getKey();
                String value = String.valueOf(entry.getValue());
                if (StringUtils.isNotEmpty(name)) {
                    nameValuePairs.add(new BasicNameValuePair(name, value));
                }
            }
        }
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpPost);
        result = consumeResponse(httpResponse);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (ParseException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    return result;
}

From source file:org.wso2.carbon.governance.registry.extensions.utils.APIUtils.java

/**
 * This method will publish api to APIM 2.0.0.
 * @param httpclient//  ww w.  j a  v a2 s. c  o  m
 * @param httppost
 * @param params
 * @param httpContext
 * @return
 */
public static ResponseAPIM callAPIMToPublishAPI2(HttpClient httpclient, HttpPost httppost,
        List<NameValuePair> params, HttpContext httpContext) throws GovernanceException {
    try {
        httppost.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8_ENCODE));
        HttpResponse response = httpclient.execute(httppost, httpContext);
        if (response.getStatusLine().getStatusCode() != Constants.CREATED_RESPONSE_CODE) { // 201 is the successful response status code
            throw new RegistryException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, Constants.UTF_8_ENCODE);
        return null;

    } catch (java.net.SocketTimeoutException e) {
        throw new GovernanceException("Connection timed out, Please check the network availability", e);
    } catch (UnsupportedEncodingException e) {
        throw new GovernanceException("Unsupported encode exception.", e);
    } catch (IOException e) {
        throw new GovernanceException("IO Exception occurred.", e);
    } catch (Exception e) {
        throw new GovernanceException(e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.governance.registry.extensions.utils.APIUtils.java

/**
 * This method will publish api to APIM.
 * @param httpclient// w  w  w. ja v a2s. c o m
 * @param httppost
 * @param params
 * @param httpContext
 * @return
 */
public static ResponseAPIM callAPIMToPublishAPI(HttpClient httpclient, HttpPost httppost,
        List<NameValuePair> params, HttpContext httpContext) throws GovernanceException {
    try {
        httppost.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8_ENCODE));
        HttpResponse response = httpclient.execute(httppost, httpContext);
        if (response.getStatusLine().getStatusCode() != Constants.SUCCESS_RESPONSE_CODE) { // 200 is the successful response status code
            throw new RegistryException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, Constants.UTF_8_ENCODE);
        Gson gson = new Gson();
        return gson.fromJson(responseString, ResponseAPIM.class);

    } catch (java.net.SocketTimeoutException e) {
        throw new GovernanceException("Connection timed out, Please check the network availability", e);
    } catch (UnsupportedEncodingException e) {
        throw new GovernanceException("Unsupported encode exception.", e);
    } catch (IOException e) {
        throw new GovernanceException("IO Exception occurred.", e);
    } catch (Exception e) {
        throw new GovernanceException(e.getMessage(), e);
    }
}

From source file:org.glowroot.tests.WebDriverIT.java

static void httpPost(String url, String content) throws Exception {
    HttpPost request = new HttpPost(url);
    request.setEntity(new StringEntity(content));
    try (CloseableHttpResponse response = httpClient.execute(request);
            InputStream responseContent = response.getEntity().getContent()) {
        ByteStreams.exhaust(responseContent);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new AssertionError("Unexpected status code: " + statusCode);
        }//from   ww w .j  ava2  s.  c  om
    }
}

From source file:com.androidinahurry.tunisiabanking.bank.atb.AtbService.java

private static HttpResponse doPost(AtbContext context, String url, List<NameValuePair> formParams)
        throws KeyManagementException, UnrecoverableKeyException, ClientProtocolException,
        NoSuchAlgorithmException, KeyStoreException, IOException {
    String URL = BASE_URL + url;

    // Create the entity for the Http Post
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, HTTP.ISO_8859_1);
    HttpPost httpPost = new HttpPost(URL);
    httpPost.setEntity(entity);

    // Execute the HTTP request
    return context.getHttpClient().execute(httpPost, context.getHttpContext());
}

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

/**
 * //from w w w  .j a  v  a 2 s.c o m
 * @param type
 *          Type of media to add: Track, Catalog, Attachment
 * 
 */
public static HttpResponse addTrack(TrustedHttpClient client, String type, InputStream media, String flavor,
        String mediaPackage) throws Exception {
    HttpPost post = new HttpPost(getServiceUrl() + "add" + type);
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("flavor", new StringBody(flavor));
    entity.addPart("mediaPackage", new StringBody(mediaPackage));
    post.setEntity(entity);
    return client.execute(post);
}

From source file:email.mandrill.SendMail.java

public static MessageResponses sendMail(Message message) {
    try {//www .j  a  v a  2s.  c  o m
        logger.log(Level.INFO, "Message:" + message.toJSONString());

        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost("https://mandrillapp.com/api/1.0/messages/send.json");

        String request = message.toJSONString();
        HttpEntity entity = new ByteArrayEntity(request.getBytes("UTF-8"));
        httppost.setEntity(entity);
        //Execute and get the response.
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity responseEntity = response.getEntity();

        if (responseEntity != null) {
            InputStream instream = responseEntity.getContent();
            try {
                StringWriter writer = new StringWriter();
                IOUtils.copy(instream, writer, "UTF-8");
                String theString = writer.toString();

                MessageResponses messageResponses = new MessageResponses(theString);
                //Do whateveer is needed with the response.
                logger.log(Level.INFO, theString);
                return messageResponses;
            } finally {
                instream.close();
            }
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, util.Utility.logMessage(e, "Exception while updating org name:", null));
    }
    return null;
}

From source file:org.fcrepo.integration.AbstractResourceIT.java

protected static HttpPost postDSMethod(final String pid, final String ds, final String content)
        throws UnsupportedEncodingException {
    final HttpPost post = new HttpPost(serverAddress + pid + "/" + ds + "/fcr:content");
    post.setEntity(new StringEntity(content));
    return post;//  ww w.  j av a2  s.c o m
}