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.example.cpulocal.myapplication_sample.samplesync.client.NetworkUtilities.java

/**
 * Connects to the SampleSync test server, authenticates the provided
 * username and password./*www.ja v  a  2  s .c  om*/
 *
 * @param username The server account username
 * @param password The server account password
 * @return String The authentication token returned by the server (or null)
 */
public static String authenticate(String username, String password) {

    final HttpResponse resp;
    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_USERNAME, username));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, password));
    final HttpEntity entity;
    try {
        entity = new UrlEncodedFormEntity(params);
    } catch (final UnsupportedEncodingException e) {
        // this should never happen.
        throw new IllegalStateException(e);
    }
    Log.i(TAG, "Authenticating to: " + AUTH_URI);
    final HttpPost post = new HttpPost(AUTH_URI);
    post.addHeader(entity.getContentType());
    post.setEntity(entity);
    try {
        resp = getHttpClient().execute(post);
        String authToken = null;
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            InputStream istream = (resp.getEntity() != null) ? resp.getEntity().getContent() : null;
            if (istream != null) {
                BufferedReader ireader = new BufferedReader(new InputStreamReader(istream));
                authToken = ireader.readLine().trim();
            }
        }
        if ((authToken != null) && (authToken.length() > 0)) {
            Log.v(TAG, "Successful authentication");
            return authToken;
        } else {
            Log.e(TAG, "Error authenticating" + resp.getStatusLine());
            return null;
        }
    } catch (final IOException e) {
        Log.e(TAG, "IOException when getting authtoken", e);
        return null;
    } finally {
        Log.v(TAG, "getAuthtoken completing");
    }
}

From source file:org.linkdroid.PostJob.java

/**
 * Posts the data to our webhook./*from w w  w .  j a v  a 2 s.  co  m*/
 * 
 * The HMAC field calculation notes:
 * <ol>
 * <li>The Extras.HMAC field is calculated from all the non Extras.STREAM
 * fields; this includes all the original bundle extra fields, plus the
 * linkdroid fields (e.g Extras.STREAM_MIME_TYPE, and including
 * Extras.STREAM_HMAC); the NONCE is NOT prepended to the input since it will
 * be somewhere in the data bundle.</li>
 * <li>The Extras.STREAM_HMAC field is calculated by digesting the concat of
 * the NONCE (first) and the actual binary data obtained from the
 * EXTRAS_STREAM uri; this STREAM_HMAC field (along with the other
 * Extras.STREAM_* fields) are added to the data bundle, which will also be
 * hmac'd.</li>
 * <li>If no hmac secret is set, then the NONCEs will not be set in the upload
 * </li>
 * </ol>
 * 
 * @param contentResolver
 * @param webhook
 * @param data
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 */
public static void execute(ContentResolver contentResolver, Bundle webhook, Bundle data)
        throws UnsupportedEncodingException, IOException, InvalidKeyException, NoSuchAlgorithmException {

    // Set constants that may be used in this method.
    final String secret = webhook.getString(WebhookColumns.SECRET);

    // This is the multipart form object that will contain all the data bundle
    // extras; it also will include the data of the extra stream and any other
    // extra linkdroid specific field required.
    MultipartEntity entity = new MultipartEntity();

    // Do the calculations to create our nonce string, if necessary.
    String nonce = obtainNonce(webhook);

    // Add the nonce to the data bundle if we have it.
    if (nonce != null) {
        data.putString(Extras.NONCE, nonce);
    }

    // We have a stream of data, so we need to add that to the multipart form
    // upload with a possible HMAC.
    if (data.containsKey(Intent.EXTRA_STREAM)) {
        Uri mediaUri = (Uri) data.get(Intent.EXTRA_STREAM);

        // Open our mediaUri, base 64 encode it and add it to our multipart upload
        // entity.
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Base64OutputStream b64os = new Base64OutputStream(baos);
        InputStream is = contentResolver.openInputStream(mediaUri);
        byte[] bytes = new byte[1024];
        int count;
        while ((count = is.read(bytes)) != -1) {
            b64os.write(bytes, 0, count);
        }
        is.close();
        baos.close();
        b64os.close();
        final String base64EncodedString = new String(baos.toByteArray(), UTF8);
        entity.addPart(Extras.STREAM, new StringBody(base64EncodedString, UTF8_CHARSET));

        // Add the mimetype of the stream to the data bundle.
        final String mimeType = contentResolver.getType(mediaUri);
        if (mimeType != null) {
            data.putString(Extras.STREAM_MIME_TYPE, mimeType);
        }

        // Do the hmac calculation of the stream and add it to the data bundle.
        // NOTE: This hmac string will be included as part of the input to the
        // other Extras hmac.
        if (shouldDoHmac(webhook)) {
            InputStream inputStream = contentResolver.openInputStream(mediaUri);
            final String streamHmac = hmacSha1(inputStream, secret, nonce);
            inputStream.close();
            data.putString(Extras.STREAM_HMAC, streamHmac);
            Log.d(TAG, "STREAM_HMAC: " + streamHmac);
        }
    }

    // Calculate the Hmac for all the items by iterating over the data bundle
    // keys in order.
    if (shouldDoHmac(webhook)) {
        final String dataHmac = calculateBundleExtrasHmac(data, secret);
        data.putString(Extras.HMAC, dataHmac);
        Log.d(TAG, "HMAC: " + dataHmac);
    }

    // Dump all the data bundle keys into the form.
    for (String k : data.keySet()) {
        Object value = data.get(k);
        // If the value is null, the key will still be in the form, but with
        // an empty string as its value.
        if (value != null) {
            entity.addPart(k, new StringBody(value.toString(), UTF8_CHARSET));
        } else {
            entity.addPart(k, new StringBody("", UTF8_CHARSET));
        }
    }

    // Create the client and request, then populate it with our multipart form
    // upload entity as part of the POST request; finally post the form.
    final String webhookUri = webhook.getString(WebhookColumns.URI);
    final HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(USER_AGENT_KEY, USER_AGENT);
    final HttpPost request = new HttpPost(webhookUri);
    request.setEntity(entity);
    HttpResponse response = client.execute(request);
    switch (response.getStatusLine().getStatusCode()) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
        break;
    default:
        throw new RuntimeException(response.getStatusLine().toString());
    }
}

From source file:Main.java

public static String getRepsonseString(String url, Map<String, String> params) {
    HttpPost request = new HttpPost(url);
    List<NameValuePair> p = new ArrayList<NameValuePair>();
    for (String key : params.keySet()) {
        p.add(new BasicNameValuePair(key, params.get(key)));
    }/*from w w  w  . ja va  2 s.  c  o m*/
    HttpClient httpClient = new DefaultHttpClient();
    String result = null;

    try {
        request.setEntity(new UrlEncodedFormEntity(p, HTTP.UTF_8));
        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            result = new String(EntityUtils.toString(response.getEntity()).getBytes("ISO_8859_1"), "UTF-8");
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (httpClient != null)
            httpClient.getConnectionManager().shutdown();
    }
    return result;
}

From source file:cardgametrackercs319.DBConnectionManager.java

public static String saveTrackScores(TrackEngine engine) throws UnsupportedEncodingException, IOException {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://ozymaxx.net/cs319/save_tracks_scores.php");

    post.setHeader("User-Agent", USER_AGENT);
    ArrayList<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("info", engine.getJSON()));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));

    HttpResponse response = client.execute(post);
    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String resLine = "";

    while ((resLine = reader.readLine()) != null) {
        result.append(resLine);// ww  w  . j  av  a 2  s  .c  o  m
    }

    return result.toString();
}

From source file:org.apache.hadoop.hdfs.qjournal.server.TestJournalNodeImageUpload.java

static HttpPost createRequest(String httpAddress, ContentBody cb) {
    HttpPost postRequest = new HttpPost(httpAddress + "/uploadImage");
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    reqEntity.addPart("file", cb);
    postRequest.setEntity(reqEntity);
    return postRequest;
}

From source file:org.smartloli.kafka.eagle.common.util.TestHttpClientUtils.java

private static HttpPost createHttpPost(Map<String, Object> dingDingMarkdownMessage) {
    if (WEBHOOK_TOKEN == null || WEBHOOK_TOKEN.trim().isEmpty()) {
        return null;
    }//from  ww w  . j  a  va  2  s  . c  om
    HttpPost httpPost = new HttpPost(WEBHOOK_TOKEN);
    httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
    StringEntity sEntity = new StringEntity(JSONObject.toJSONString(dingDingMarkdownMessage), "utf-8");
    httpPost.setEntity(sEntity);
    return httpPost;
}

From source file:com.flurry.proguard.UploadProGuardMapping.java

/**
 * Register this upload with the metadata service
 *
 * @param projectId the id of the project
 * @param payload the JSON body to send// ww w  .j av a2 s.  c o  m
 * @param token the Flurry auth token
 * @return the id of the created upload
 */
private static String createUpload(String projectId, String payload, String token) {
    String postUrl = String.format("%s/project/%s/uploads", METADATA_BASE, projectId);
    List<Header> requestHeaders = getMetadataHeaders(token);
    HttpPost postRequest = new HttpPost(postUrl);
    postRequest.setEntity(new StringEntity(payload, Charset.forName("UTF-8")));
    HttpResponse response = executeHttpRequest(postRequest, requestHeaders);
    expectStatus(response, HttpURLConnection.HTTP_CREATED);

    JSONObject jsonObject = getJsonFromEntity(response.getEntity());
    return jsonObject.getJSONObject("data").get("id").toString();
}

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

/**
 * //from  w ww . jav a2s  .c om
 * @param channel
 *          Distribution channel: local, youtube, itunesu
 * 
 */
public static HttpResponse distribute(TrustedHttpClient client, String channel, String mediapackage,
        String... elementId) throws Exception {
    HttpPost post = new HttpPost(getServiceUrl() + channel.toLowerCase() + "/");
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("mediapackage", mediapackage));
    for (String id : elementId) {
        params.add(new BasicNameValuePair("elementId", id));
    }
    post.setEntity(new UrlEncodedFormEntity(params));

    return client.execute(post);
}

From source file:org.wso2.carbon.governance.registry.extensions.executors.apistore.APIDeleteExecutor.java

/**
 * This method will publish api to APIM.
 *
 * @param httpclient  HttpClient//from  ww w  .  j av a  2 s  . c  o m
 * @param httppost    HttpPost
 * @param params      List of NameValuePair
 * @param httpContext HttpContext
 * @return ResponseAPIM
 */
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 RuntimeException(
                    "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:UnitTest4.java

public static void execute()
        throws ClientProtocolException, IOException, InterruptedException, ExecutionException {
    /*// w w  w  . j  av  a 2 s.  co m
      CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
      try {
    httpclient.start();
    HttpGet request = new HttpGet("http://www.apache.org/");
    Future<HttpResponse> future = httpclient.execute(request, null);
    HttpResponse response = future.get();
    System.out.println("Response: " + response.getStatusLine());
    System.out.println("Shutting down");
      } finally {
    httpclient.close();
      }
      System.out.println("Done");
    */

    /*
    try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault()) {
        httpclient.start();
        HttpPost request = new HttpPost(addr);
        StringEntity entity = new StringEntity(event, ContentType.create("application/json", Consts.UTF_8));
        request.setEntity(entity);
        httpclient.execute(request, null);
    } catch (Exception e) {
        LOG.error("Failed to sending event", e);
    }
    */
    //Asserts a;
    CloseableHttpAsyncClient m_httpClient = HttpAsyncClients.createDefault();

    m_httpClient.start();

    HttpHost m_target = new HttpHost("localhost", 5000, "http");
    //HttpPost postRequest = new HttpPost("http://localhost:5000/hello");
    HttpPost postRequest = new HttpPost("/");

    StringEntity params = new StringEntity("");

    postRequest.addHeader("content-type", "application/json");
    postRequest.setEntity(params);

    log.debug("execute() executing request to " + m_target);

    //HttpAsyncRequestConsumer<HttpRequest> gh;

    // works HttpResponse httpResponse = httpClient.execute(target, getRequest);
    Future<HttpResponse> future = m_httpClient.execute(m_target, postRequest, null);
    //Future<HttpResponse> future = m_httpClient.execute(postRequest, null);
    //HttpResponse httpResponse = future.get();
    while (future.isDone() == false) {
        log.debug("Inside while");
    }
    HttpResponse httpResponse = null;
    try {
        httpResponse = future.get(100, TimeUnit.NANOSECONDS);
    } catch (TimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    HttpEntity entity = httpResponse.getEntity();

    log.debug("execute()----------------------------------------");
    log.debug("execute() {}", httpResponse.getStatusLine());
    Header[] headers = httpResponse.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        log.debug("execute() {}", headers[i]);
    }
    log.debug("execute()----------------------------------------");

    String jsonString = null;
    if (entity != null) {
        jsonString = EntityUtils.toString(entity);
        log.debug("execute() {}", jsonString);
    }

}