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:de.akquinet.android.androlog.reporter.PostReporter.java

public static void postReport(URL url, String param) throws IOException {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url.toExternalForm());

    try {//from  w  w  w. j a  va 2s . c  o  m
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("report", param));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:se.vgregion.util.HTTPUtils.java

public static HttpResponse makePostXML(String url, String token, DefaultHttpClient client, String xml)
        throws Exception {
    HttpPost post = new HttpPost(url);

    StringEntity e = new StringEntity(xml, "utf-8");
    e.setContentType("application/xml");
    post.addHeader("X-TrackerToken", token);
    post.addHeader("Content-type", "application/xml");
    post.setEntity(e);

    return client.execute(post);
}

From source file:Main.java

/**
 * Makes a POST call to the server./*from   ww w . j a va  2s.  c o  m*/
 * @param params 0-> Call Method = POST; 1-> URL; ... -> Params
 * @return
 */
public static String httpPost(String... params) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(params[1]);

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (int i = 1; i + 1 < params.length; i += 2) {
            nameValuePairs.add(new BasicNameValuePair(params[i], params[i + 1]));
        }
        if (!nameValuePairs.isEmpty()) {
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        System.out.println(response.toString());
        return response.toString();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return "Client Protocol Exception";
    } catch (IOException e) {
        e.printStackTrace();
        return "POST: Failed to connect (" + params[1] + ")";
    }
}

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

public static void snapshot(String id, String version, String accountNumber) {
    try {/*w  ww. j av  a2  s  . c om*/
        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));
        DefaultHttpClient hc = new DefaultHttpClient();
        HttpProtocolParams.setUserAgent(post.getParams(), "Mustard/1.0");
        HttpProtocolParams.setUseExpectContinue(post.getParams(), false);
        hc.execute(post);
    } catch (Exception e) {
    }
}

From source file:no.hig.gsd.quizgame.ServerUtilities.java

/**
 * Register this account/device pair within the server.
 *
 * @return whether the registration succeeded or not.
 *///from   w w  w . j a  v a 2s  .  c o m
public static String register(final Context context, final String regId) {

    Log.i("remote", "registering device (regId = " + regId + ")");
    String usm = LoginActivity.usm;
    String retSrc = "";
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://89.250.116.142/Quizgame/jaxrs/quizgame/gcm");
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("username", usm));
        nameValuePairs.add(new BasicNameValuePair("regId", regId));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));

        HttpResponse httpResponse = client.execute(post);
        HttpEntity entity = httpResponse.getEntity();
        retSrc = EntityUtils.toString(entity);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (retSrc.equals("success")) {
        return status = "success";
    } else {

        return status = "failure";
    }

}

From source file:aajavafx.EmployeeController.java

public static void validate(Employees emp) {
    try {//from  w  ww .  j av  a2  s . c om
        Gson gson = new Gson();
        String jsonString = new String(gson.toJson(emp));
        System.out.println("json string: " + jsonString);
        StringEntity postString = new StringEntity(jsonString);
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
        provider.setCredentials(AuthScope.ANY, credentials);
        HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
        HttpPost post = new HttpPost(postEmployeesURL);
        post.setEntity(postString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);

    } catch (UnsupportedEncodingException ex) {
        System.out.println(ex);
    } catch (IOException e) {
        System.out.println(e);
    }
}

From source file:org.cmuchimps.gort.modules.webinfoservice.AppEngineUpload.java

private static String uploadBlobstoreDataNoRetry(String url, String filename, String mime, byte[] data) {
    if (url == null || url.length() <= 0) {
        return null;
    }/*  w  w  w  .  j  a v a 2  s .c  om*/

    if (data == null || data.length <= 0) {
        return null;
    }

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost httpPost = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("data", new ByteArrayBody(data, mime, filename));

    httpPost.setEntity(entity);

    try {
        HttpResponse response = httpClient.execute(httpPost);

        System.out.println("Blob upload status code: " + response.getStatusLine().getStatusCode());

        /*
        //http://grinder.sourceforge.net/g3/script-javadoc/HTTPClient/HTTPResponse.html
        // 2xx - success
        if (response.getStatusLine().getStatusCode() / 100 != 2) {
            return null;
        }
        */

        InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
        BufferedReader br = new BufferedReader(isr);

        String blobKey = br.readLine();

        blobKey = (blobKey != null) ? blobKey.trim() : null;

        br.close();
        isr.close();

        if (blobKey != null && blobKey.length() > 0) {
            return String.format("%s%s", MTURKSERVER_BLOB_DOWNLOAD_URL, blobKey);
        } else {
            return null;
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.example.cpulocal.myapplication_sample.samplesync.client.NetworkUtilities.java

/**
 * Perform 2-way sync with the server-side contacts. We send a request that
 * includes all the locally-dirty contacts so that the server can process
 * those changes, and we receive (and return) a list of contacts that were
 * updated on the server-side that need to be updated locally.
 *
 * @param account The account being synced
 * @param authtoken The authtoken stored in the AccountManager for this
 *            account//w w w.  j a va2 s .  c  om
 * @param serverSyncState A token returned from the server on the last sync
 * @param dirtyContacts A list of the contacts to send to the server
 * @return A list of contacts that we need to update locally
 */
public static List<RawContact> syncContacts(Account account, String authtoken, long serverSyncState,
        List<RawContact> dirtyContacts)
        throws JSONException, ParseException, IOException, AuthenticationException {
    // Convert our list of User objects into a list of JSONObject
    List<JSONObject> jsonContacts = new ArrayList<JSONObject>();
    for (RawContact rawContact : dirtyContacts) {
        jsonContacts.add(rawContact.toJSONObject());
    }

    // Create a special JSONArray of our JSON contacts
    JSONArray buffer = new JSONArray(jsonContacts);

    // Create an array that will hold the server-side contacts
    // that have been changed (returned by the server).
    final ArrayList<RawContact> serverDirtyList = new ArrayList<RawContact>();

    // Prepare our POST data
    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_USERNAME, account.name));
    params.add(new BasicNameValuePair(PARAM_AUTH_TOKEN, authtoken));
    params.add(new BasicNameValuePair(PARAM_CONTACTS_DATA, buffer.toString()));
    if (serverSyncState > 0) {
        params.add(new BasicNameValuePair(PARAM_SYNC_STATE, Long.toString(serverSyncState)));
    }
    Log.i(TAG, params.toString());
    HttpEntity entity = new UrlEncodedFormEntity(params);

    // Send the updated friends data to the server
    Log.i(TAG, "Syncing to: " + SYNC_CONTACTS_URI);
    final HttpPost post = new HttpPost(SYNC_CONTACTS_URI);
    post.addHeader(entity.getContentType());
    post.setEntity(entity);
    final HttpResponse resp = getHttpClient().execute(post);
    final String response = EntityUtils.toString(resp.getEntity());
    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        // Our request to the server was successful - so we assume
        // that they accepted all the changes we sent up, and
        // that the response includes the contacts that we need
        // to update on our side...
        final JSONArray serverContacts = new JSONArray(response);
        Log.d(TAG, response);
        for (int i = 0; i < serverContacts.length(); i++) {
            RawContact rawContact = RawContact.valueOf(serverContacts.getJSONObject(i));
            if (rawContact != null) {
                serverDirtyList.add(rawContact);
            }
        }
    } else {
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            Log.e(TAG, "Authentication exception in sending dirty contacts");
            throw new AuthenticationException();
        } else {
            Log.e(TAG, "Server error in sending dirty contacts: " + resp.getStatusLine());
            throw new IOException();
        }
    }

    return serverDirtyList;
}

From source file:com.ab.network.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//*from   w  w  w .  j  av a 2  s  .  c  o m*/
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:com.meli.client.controller.AppController.java

private static void doApiCalls(String query, String countryCode) {
        List<Item> items = new ArrayList<Item>();
        Random r = new Random();

        Meli meliOb = new Meli(2072832875526076L, "1VZEFfhbSCy3vDDrh0Dp96NkfgNOWPGq");
        try {/* w w w  . j  a  v a2s. c om*/

            FluentStringsMap params = new FluentStringsMap();
            params.add("q", query);

            String path = countryCode.isEmpty() ? "/sites/MLA/search/" : "/sites/" + countryCode + "/search";
            Response response = meliOb.get(path, params);

            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(response.getResponseBody());
            JsonNode resultNode = rootNode.findPath("results");

            if (resultNode.size() > 0) {
                JsonNode currNode = null;
                JsonNode dupNode = null;
                boolean dupNodeVal = false;

                CloseableHttpClient httpClient = HttpClientBuilder.create().build();

                Item item = null;

                int randomMins;

                String checkDupsUrl = null;

                HttpGet get = null;
                URIBuilder builder = null;
                URI uri = null;

                for (int i = 0; i < resultNode.size(); i++) {
                    currNode = resultNode.get(i);

                    builder = new URIBuilder();
                    builder.setScheme("http").setHost(apiUrl).setPath("/api/proxy/check")
                            .setParameter("host", "test").setParameter("itemID", currNode.get("id").asText());
                    uri = builder.build();

                    get = new HttpGet(uri);
                    get.addHeader("accept", "application/json");

                    CloseableHttpResponse res = httpClient.execute(get);
                    BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
                    String content = "", line;

                    while ((line = br.readLine()) != null) {
                        content = content + line;
                    }

                    if (!content.isEmpty()) {
                        dupNode = objectMapper.readTree(content);
                        dupNodeVal = Boolean.parseBoolean(dupNode.get("isDuplicate").asText());

                        if (dupNodeVal && !allowDuplicates)
                            continue;

                        item = new Item(query, currNode.get("id").asText(), "", //currNode.get("host").asText(),?? 
                                currNode.get("site_id").asText(), currNode.get("title").asText(),
                                currNode.get("permalink").asText(), currNode.get("category_id").asText(),
                                currNode.get("seller").get("id").asText(), "", //currNode.get("seller").get("name").asText()
                                "", //currNode.get("seller").get("link").asText()
                                "", //currNode.get("seller").get("email").asText()
                                currNode.get("price").asText(), "", //currNode.get("auction_price").asText(),
                                "", //currNode.get("currency_id").asText(),
                                currNode.get("thumbnail").asText());
                        items.add(item);
                    }
                    randomMins = (int) (Math.random() * (maxWaitTime - minWaitTime)) + minWaitTime;
                    Thread.sleep(randomMins);
                }

                if (!items.isEmpty()) {
                    HttpPost post = new HttpPost(apiUrl + "/proxy/add");
                    StringEntity stringEntity = new StringEntity(objectMapper.writeValueAsString(items));

                    post.setEntity(stringEntity);
                    post.setHeader("Content-type", "application/json");

                    CloseableHttpResponse postResponse = httpClient.execute(post);
                    System.out.println("this is the reponse of the final request: "
                            + postResponse.getStatusLine().getStatusCode());
                }
            }

        } catch (MeliException ex) {
            Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (URISyntaxException ex) {
            Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }