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.flurry.proguard.UploadProGuardMapping.java

/**
 * Upload the archive to Flurry//ww w . java 2 s  .c o  m
 *
 * @param file the archive to send
 * @param projectId the project's id
 * @param uploadId the the upload's id
 * @param token the Flurry auth token
 */
private static void sendToUploadService(File file, String projectId, String uploadId, String token) {
    String uploadServiceUrl = String.format("%s/upload/%s/%s", UPLOAD_BASE, projectId, uploadId);
    List<Header> requestHeaders = getUploadServiceHeaders(file.length(), token);
    HttpPost postRequest = new HttpPost(uploadServiceUrl);
    postRequest.setEntity(new FileEntity(file));
    HttpResponse response = executeHttpRequest(postRequest, requestHeaders);
    expectStatus(response, HttpURLConnection.HTTP_CREATED, HttpURLConnection.HTTP_ACCEPTED);
}

From source file:com.geertvanderploeg.kiekeboek.client.NetworkUtilities.java

/**
 * Connects to the server, authenticates the provided username and
 * password./* w ww  .  j a  va 2s  . co  m*/
 * 
 * @param username The user's username
 * @param password The user's password
 * @param handler The hander instance from the calling UI thread.
 * @param context The context of the calling Activity.
 * @return boolean The boolean result indicating whether the user was
 *         successfully authenticated.
 */
public static boolean authenticate(String username, String password, Handler handler, final Context context) {
    final HttpResponse resp;

    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("_method", "POST"));
    params.add(new BasicNameValuePair(PARAM_USERNAME, username));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, password));
    HttpEntity entity = null;
    try {
        entity = new UrlEncodedFormEntity(params);
    } catch (final UnsupportedEncodingException e) {
        // this should never happen.
        throw new AssertionError(e);
    }
    final HttpPost post = new HttpPost(context.getString(AUTH_URI_RESOURCE));
    post.addHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded"));
    post.setEntity(entity);
    HttpClient localHttpClient = getHttpClient();
    Log.d(TAG, "POST-ing params to URL '" + context.getString(AUTH_URI_RESOURCE) + "': " + params);
    try {
        resp = localHttpClient.execute(post);
        Log.d(TAG, "Authentication response status line: " + resp.getStatusLine());
        Log.d(TAG, "Authentication response headers: " + Arrays.asList(resp.getAllHeaders()));
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY
                && resp.getHeaders("Location") != null
                && resp.getHeaders("Location")[0].getValue().contains("/intranet/people")) {
            Log.v(TAG, "Successful authentication");
            sendResult(true, handler, context);
            resp.getEntity().consumeContent();
            return true;
        } else {
            Log.v(TAG, "Error authenticating " + resp.getStatusLine());
            sendResult(false, handler, context);
            resp.getEntity().consumeContent();
            return false;
        }
    } catch (final IOException e) {
        Log.v(TAG, "IOException when getting authtoken", e);
        sendResult(false, handler, context);
        return false;
    } finally {
        Log.v(TAG, "getAuthtoken completing");
    }
}

From source file:Main.java

public static String postReqAsJsonAddParam(String uri, String requestJson, Map<String, String> param)
        throws ClientProtocolException, IOException {
    Log.i(TAG, "Send data to :" + uri + " ========== and the data str:" + requestJson);
    HttpPost post = new HttpPost(uri);
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    for (Map.Entry<String, String> entry : param.entrySet()) {
        parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }//from w  w w. j av  a 2s  . c  om
    parameters.add(new BasicNameValuePair("attendanceClientJSON", requestJson));
    post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(post);
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        String retStr = EntityUtils.toString(response.getEntity());
        Log.i(TAG, "=================response str:" + retStr);
        return retStr;
    }

    return response.getStatusLine().getStatusCode() + "ERROR";
}

From source file:eu.ttbox.androgister.sync.client.NetworkUtilities.java

/**
 * Connects to the SampleSync test server, authenticates the provided
 * username and password.//w  w  w  . ja va  2s  .c o  m
 *
 * @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) {
    if (true) {
        // TOFO Supp  Mock
        return "xyz";
    }
    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) {
                try {
                    BufferedReader ireader = new BufferedReader(new InputStreamReader(istream));
                    authToken = ireader.readLine().trim();
                    ireader.close();
                } finally {
                    istream.close();
                }
            }
        }
        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.apiwatch.util.IO.java

public static void putAPIData(APIScope scope, String format, String encoding, String location, String username,
        String password) throws SerializationError, IOException, HttpException {
    if (URL_RX.matcher(location).matches()) {
        DefaultHttpClient client = new DefaultHttpClient();
        if (username != null && password != null) {
            client.getCredentialsProvider().setCredentials(new AuthScope(null, -1),
                    new UsernamePasswordCredentials(username, password));
        }//from w  ww .ja v a  2 s  .  co  m
        HttpPost req = new HttpPost(location);
        StringWriter writer = new StringWriter();
        Serializers.dumpAPIScope(scope, writer, format);
        HttpEntity entity = new StringEntity(writer.toString(), encoding);
        req.setEntity(entity);
        req.setHeader("content-type", format);
        req.setHeader("content-encoding", encoding);
        HttpResponse response = client.execute(req);
        client.getConnectionManager().shutdown();
        if (response.getStatusLine().getStatusCode() >= 400) {
            throw new HttpException(response.getStatusLine().getReasonPhrase());
        }
        LOGGER.info("Sent results to URL: " + location);
    } else {
        File dir = new File(location);
        dir.mkdirs();
        File file = new File(dir, "api." + format);
        OutputStream out = new FileOutputStream(file);
        Writer writer = new OutputStreamWriter(out, encoding);
        Serializers.dumpAPIScope(scope, writer, format);
        writer.flush();
        writer.close();
        out.close();
        LOGGER.info("Wrote results to file: " + file);
    }
}

From source file:ch.ralscha.extdirectspring_itest.RawJsonControllerTest.java

@SuppressWarnings("unchecked")
private static void testAndCheck(String action, String method, Integer total, boolean success)
        throws IOException, JsonParseException, JsonMappingException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;
    try {// w  w w.  ja  v  a  2s.  co m
        HttpPost post = new HttpPost("http://localhost:9998/controller/router");

        StringEntity postEntity = new StringEntity("{\"action\":\"" + action + "\",\"method\":\"" + method
                + "\",\"data\":[],\"type\":\"rpc\",\"tid\":1}", "UTF-8");
        post.setEntity(postEntity);
        post.setHeader("Content-Type", "application/json; charset=UTF-8");

        response = client.execute(post);
        HttpEntity entity = response.getEntity();
        assertThat(entity).isNotNull();
        String responseString = EntityUtils.toString(entity);

        assertThat(responseString).isNotNull();
        assertThat(responseString).startsWith("[").endsWith("]");

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> rootAsMap = mapper
                .readValue(responseString.substring(1, responseString.length() - 1), Map.class);
        assertEquals(5, rootAsMap.size());

        assertEquals(method, rootAsMap.get("method"));
        assertEquals("rpc", rootAsMap.get("type"));
        assertEquals(action, rootAsMap.get("action"));
        assertEquals(1, rootAsMap.get("tid"));

        Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result");
        if (total != null) {
            assertEquals(3, result.size());
            assertThat((Integer) result.get("total")).isEqualTo(total);
        } else {
            assertEquals(2, result.size());
        }
        assertThat((Boolean) result.get("success")).isEqualTo(success);

        List<Map<String, Object>> records = (List<Map<String, Object>>) result.get("records");
        assertEquals(2, records.size());

        assertEquals("4cf8e5b8924e23349fb99454", ((Map<String, Object>) records.get(0).get("_id")).get("$oid"));
        assertEquals("4cf8e5b8924e2334a0b99454", ((Map<String, Object>) records.get(1).get("_id")).get("$oid"));
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.leprechaun.solveig.http.RequestExecutor.java

public static ResponseEntity intermediateExcutor(String host, String port, String dbName, String username,
        String password, String query) throws Exception {

    ResponseEntity responseEntity = new ResponseEntity();

    //INSERT/* w ww  .j ava  2s. co  m*/

    if (query.toLowerCase().contains("insert")) {

        //query.replaceFirst("insert", "");

        query = query.substring(7);

        HttpClient client = new DefaultHttpClient();
        String url = "http://" + host + ":" + port + "/write?";

        if (!dbName.isEmpty() || dbName == null) {
            url += "db=" + dbName + "&";
        }

        if (!username.isEmpty() || username == null) {
            url += "u=" + username + "&";
        }
        if (!password.isEmpty() || password == null) {
            url += "u=" + password + "&";
        }

        if (url.toCharArray()[url.toCharArray().length - 1] == '&') {
            url = url.substring(0, url.toCharArray().length - 1);
        }

        //String body = requestFormatter(query);
        HttpPost post = new HttpPost(url);

        System.out.println(query);

        HttpEntity httpEntity = new ByteArrayEntity(query.getBytes("UTF-8"));
        post.setEntity(httpEntity);

        try {
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            /*String responseString = EntityUtils.toString(entity, "UTF-8");
            System.out.println(responseString);
                    
            responseEntity.setCode(response.getStatusLine().toString());
            responseEntity.setBody(responseString);*/
            responseEntity.setCode("OK");
            responseEntity.setBody("");
        } catch (IOException e) {
            System.out.println(e.getMessage());

            responseEntity.setCode("ERROR");
            responseEntity.setBody(e.getMessage());
        }

    } //SELECT
    else {

        HttpClient client = new DefaultHttpClient();

        String url = "http://" + host + ":" + port + "/query?";

        if (!dbName.isEmpty() || dbName == null) {
            url += "db=" + dbName + "&";
        }

        if (!username.isEmpty() || username == null) {
            url += "u=" + username + "&";
        }
        if (!password.isEmpty() || password == null) {
            url += "u=" + password + "&";
        }

        url += "q=" + requestFormatter(query);

        HttpGet get = new HttpGet(url);

        try {
            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity, "UTF-8");
            System.out.println(responseString);

            responseEntity.setCode(response.getStatusLine().toString());
            responseEntity.setBody(responseString);
        } catch (IOException e) {
            System.out.println(e.getMessage());

            responseEntity.setCode("ERROR");
            responseEntity.setBody(e.getMessage());
        }
    }

    return responseEntity;
}

From source file:myexamples.dbase.MyHelpMethods.java

public static String sendHttpRequest2(String url, String requestBody, String requestType) throws IOException {
    String result = null;/*from w w w.ja v a2  s.  c om*/
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse httpResponse;
    try {
        switch (requestType) {
        case "Get":
            httpResponse = httpclient.execute(new HttpGet(url));
            break;
        case "Post":
            HttpPost httppost = new HttpPost(url);
            if (requestBody != null)
                httppost.setEntity(new StringEntity(requestBody));
            httpResponse = httpclient.execute(httppost);
            break;
        case "Put":
            HttpPut httpPut = new HttpPut(url);
            httpPut.addHeader("Content-Type", "application/json");
            httpPut.addHeader("Accept", "application/json");
            if (requestBody != null)
                httpPut.setEntity(new StringEntity(requestBody, DEFAULT_CHARSET));
            httpResponse = httpclient.execute(httpPut);
            break;
        case "Delete":
            httpResponse = httpclient.execute(new HttpDelete(url));
            break;
        default:
            httpResponse = httpclient.execute(new HttpGet(url));
            break;
        }
        try {
            HttpEntity entity1 = httpResponse.getEntity();
            if (entity1 != null) {
                long len = entity1.getContentLength();
                if (len != -1 && len < MAX_CONTENT_LENGTH) {
                    result = EntityUtils.toString(entity1, DEFAULT_CHARSET);
                } else {
                    System.out.println("Error!!!! entity length=" + len);
                }
            }
            EntityUtils.consume(entity1);
        } finally {
            httpResponse.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        httpclient.close();
    }
    return result;
}

From source file:org.mumod.util.MustardUtil.java

public static void snapshot(Context context, String id, String version, String accountNumber) {
    try {/*from  ww w .  j  a  v a2 s.  c  o  m*/
        HttpPost post = new HttpPost("http://mustard.macno.org/snapshot.php");
        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("v", version));
        params.add(new BasicNameValuePair("n", accountNumber));
        params.add(new BasicNameValuePair("m", id));
        post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        HttpManager hm = new HttpManager(context);
        DefaultHttpClient hc = hm.getHttpClient();
        hc.execute(post);
    } catch (Exception e) {
    }
}

From source file:com.graphaware.test.util.TestUtils.java

/**
 * Issue an HTTP POST and assert the response status code.
 *
 * @param url                to POST to.
 * @param json               request body.
 * @param headers            request headers as map.
 * @param expectedStatusCode expected status code.
 * @return the body of the response./* w ww .j  a  v  a2 s. co m*/
 */
public static String post(String url, String json, Map<String, String> headers, final int expectedStatusCode) {
    HttpPost post = new HttpPost(url);
    if (json != null) {
        post.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
    }

    setHeaders(post, headers);

    return method(post, expectedStatusCode);
}