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:brooklyn.networking.cloudstack.HttpUtil.java

public static HttpToolResponse httpPost(HttpClient httpClient, URI uri, Multimap<String, String> headers,
        byte[] body) {
    HttpPost httpPost = new HttpPost(uri);
    for (Map.Entry<String, String> entry : headers.entries()) {
        httpPost.addHeader(entry.getKey(), entry.getValue());
    }/*  ww  w  .j av a2s . com*/
    if (body != null) {
        HttpEntity httpEntity = new ByteArrayEntity(body);
        httpPost.setEntity(httpEntity);
    }

    long startTime = System.currentTimeMillis();
    try {
        HttpResponse httpResponse = httpClient.execute(httpPost);

        try {
            return new HttpToolResponse(httpResponse, startTime);
        } finally {
            EntityUtils.consume(httpResponse.getEntity());
        }
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
}

From source file:driimerfinance.helpers.FinanceHelper.java

/**
* Checks if the license is valid using the License Key Server
* 
* @param license key to check/*from   ww  w  .  ja v a2s  .  c  o  m*/
* @return validity of the license (true or false)
*/
public static boolean checkLicense(String licenseKey) {
    HttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost("http://driimerfinance.michaelkohler.info/checkLicense");
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("key", licenseKey)); // pass the key to the server
    try {
        httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        return false;
    }

    HttpResponse response = null;
    try {
        response = httpclient.execute(httppost); // get the response from the server
    } catch (IOException e) {
        return false;
    }
    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream instream = null;
        try {
            instream = entity.getContent();
            @SuppressWarnings("resource")
            java.util.Scanner s = new java.util.Scanner(instream).useDelimiter("\\A"); // parse the response
            String responseString = s.hasNext() ? s.next() : "";
            instream.close();
            return responseString.contains("\"valid\":true"); // if the license is valid, return true, else false
        } catch (IllegalStateException | IOException e) {
            return false;
        }
    }
    return false;
}

From source file:edu.cmu.android.restaurant.authentication.NetworkUtilities.java

/**
 * Fetches the list of friend data updates from the server
 * //from   ww  w  . ja v  a 2  s .  c o  m
 * @param account
 *            The account being synced.
 * @param authtoken
 *            The authtoken stored in AccountManager for this account
 * @param lastUpdated
 *            The last time that sync was performed
 * @return list The list of updates received from the server.
 */
public static List<User> fetchFriendUpdates(Account account, String authtoken, Date lastUpdated)
        throws JSONException, ParseException, IOException, AuthenticationException {
    final ArrayList<User> friendList = new ArrayList<User>();
    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_USERNAME, account.name));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, authtoken));
    if (lastUpdated != null) {
        final SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        params.add(new BasicNameValuePair(PARAM_UPDATED, formatter.format(lastUpdated)));
    }
    Log.i(TAG, params.toString());

    HttpEntity entity = null;
    entity = new UrlEncodedFormEntity(params);
    final HttpPost post = new HttpPost(FETCH_FRIEND_UPDATES_URI);
    post.addHeader(entity.getContentType());
    post.setEntity(entity);
    maybeCreateHttpClient();

    final HttpResponse resp = mHttpClient.execute(post);
    final String response = EntityUtils.toString(resp.getEntity());

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        // Succesfully connected to the samplesyncadapter server and
        // authenticated.
        // Extract friends data in json format.
        final JSONArray friends = new JSONArray(response);
        Log.d(TAG, response);
        for (int i = 0; i < friends.length(); i++) {
            friendList.add(User.valueOf(friends.getJSONObject(i)));
        }
    } else {
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            Log.e(TAG, "Authentication exception in fetching remote contacts");
            throw new AuthenticationException();
        } else {
            Log.e(TAG, "Server error in fetching remote contacts: " + resp.getStatusLine());
            throw new IOException();
        }
    }
    return friendList;
}

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

/**
 * Upload the archive to Flurry/*  ww  w .  ja v  a  2  s. c  om*/
 *
 * @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)
        throws IOException {
    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));
    try (CloseableHttpResponse response = executeHttpRequest(postRequest, requestHeaders)) {
        expectStatus(response, HttpURLConnection.HTTP_CREATED, HttpURLConnection.HTTP_ACCEPTED);
    } finally {
        postRequest.releaseConnection();
    }
}

From source file:com.android.bandwidthtest.util.BandwidthTestUtil.java

/**
 * Post a given file for a given device and timestamp to the server.
 * @param server {@link String} url of test server
 * @param deviceId {@link String} device id that is uploading
 * @param timestamp {@link String} timestamp
 * @param file {@link File} to upload/*from w w w.  j av  a 2s  . co m*/
 * @return true if it succeeded
 */
public static boolean postFileToServer(String server, String deviceId, String timestamp, File file) {
    try {
        Log.d(LOG_TAG, "Uploading begining");
        HttpClient httpClient = new DefaultHttpClient();
        String uri = server;
        if (!uri.endsWith("/")) {
            uri += "/";
        }
        uri += "upload";
        Log.d(LOG_TAG, "Upload url:" + uri);
        HttpPost postRequest = new HttpPost(uri);
        Part[] parts = { new StringPart("device_id", deviceId), new StringPart("timestamp", timestamp),
                new FilePart("file", file) };
        MultipartEntity reqEntity = new MultipartEntity(parts, postRequest.getParams());
        postRequest.setEntity(reqEntity);
        HttpResponse res = httpClient.execute(postRequest);
        res.getEntity().getContent().close();
    } catch (IOException e) {
        Log.e(LOG_TAG, "Could not upload file with error: " + e);
        return false;
    }
    return true;
}

From source file:org.factpub.ui.gui.network.PostFile.java

public static List<String> uploadToFactpub(File file) throws Exception {
    List<String> status = new ArrayList<String>();
    int i = 0;//  www. ja va2s  .com

    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    String postUrl = FEConstants.SERVER_POST_HANDLER + "?id=" + AuthMediaWikiIdHTTP.authorisedUser + "&ps="
            + AuthMediaWikiIdHTTP.userPassword;

    HttpPost httppost = new HttpPost(postUrl);

    System.out.println(postUrl);

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "json");

    // name must be "uploadfile". this is same on the server side.
    mpEntity.addPart(FEConstants.SERVER_UPLOAD_FILE_NAME, cbFile);

    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());

    if (response.getStatusLine().toString().contains("502 Bad Gateway")) {
        status.add("Looks server is down.");
    } else {
        if (resEntity != null) {
            status.add(EntityUtils.toString(resEntity));
            System.out.println(status.get(i));
            i++;
        }

        if (resEntity != null) {
            resEntity.consumeContent();
        }
    }
    httpclient.getConnectionManager().shutdown();

    //String status = "Upload Success!";
    return status;
}

From source file:com.github.egonw.rrdf.RJenaHelper.java

public static StringMatrix sparqlRemoteNoJena(String endpoint, String queryString, String user, String password)
        throws Exception {
    StringMatrix table = null;/*from  www.jav a  2  s.c om*/

    // use Apache for doing the SPARQL query
    DefaultHttpClient httpclient = new DefaultHttpClient();

    // Set credentials on the client
    if (user != null) {
        URL endpointURL = new URL(endpoint);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(endpointURL.getHost(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(user, password));
        httpclient.setCredentialsProvider(credsProvider);
    }

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("query", queryString));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    HttpPost httppost = new HttpPost(endpoint);
    httppost.setEntity(entity);
    HttpResponse response = httpclient.execute(httppost);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode != 200)
        throw new HttpException(
                "Expected HTTP 200, but got a " + statusCode + ": " + statusLine.getReasonPhrase());

    HttpEntity responseEntity = response.getEntity();
    InputStream in = responseEntity.getContent();

    // now the Jena part
    ResultSet results = ResultSetFactory.fromXML(in);
    // also use Jena for getting the prefixes...
    Query query = QueryFactory.create(queryString);
    PrefixMapping prefixMap = query.getPrefixMapping();
    table = convertIntoTable(prefixMap, results);

    in.close();
    return table;
}

From source file:com.avinashbehera.sabera.network.HttpClient.java

public static JSONObject SendHttpPostUsingHttpClient(String URL, JSONObject jsonObjSend) {

    try {/*w  ww  . j  av  a2  s .  c o  m*/
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 60 * 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 60 * 1000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        //httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        //httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression

        long t = System.currentTimeMillis();
        Log.d(TAG, "httpPostReuest = " + httpPostRequest.toString());
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString = convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONParser parser = new JSONParser();
            JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;
        }

    } catch (Exception e) {
        Log.d(TAG, "catch block");
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    Log.d(TAG, "SendHttpPostUsingHttpClient returning null");
    return null;
}

From source file:com.glaf.core.util.http.HttpClientUtils.java

public static String doPost(String url, String data, String contentType, String encoding) {
    StringBuffer buffer = new StringBuffer();
    InputStreamReader is = null;//  w ww  .  j  a  v a 2s.  co m
    BufferedReader reader = null;
    BasicCookieStore cookieStore = new BasicCookieStore();
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.setDefaultCookieStore(cookieStore).build();
    try {
        HttpPost post = new HttpPost(url);
        if (data != null) {
            StringEntity entity = new StringEntity(data, encoding);
            post.setHeader("Content-Type", contentType);
            post.setEntity(entity);
        }
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        is = new InputStreamReader(entity.getContent(), encoding);
        reader = new BufferedReader(is);
        String tmp = reader.readLine();
        while (tmp != null) {
            buffer.append(tmp);
            tmp = reader.readLine();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(reader);
        IOUtils.closeStream(is);
        try {
            client.close();
        } catch (IOException ex) {
        }
    }
    return buffer.toString();
}

From source file:com.alphabetbloc.accessmrs.utilities.NetworkUtils.java

public static DataInputStream getOdkStream(HttpClient client, String url) throws Exception {

    // get prefs/*from  w  w  w.j a  v a  2 s . c  o m*/
    HttpPost request = new HttpPost(url);
    request.setEntity(new OdkAuthEntity());
    HttpResponse response = client.execute(request);
    response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = response.getEntity();

    DataInputStream zdis = new DataInputStream(new GZIPInputStream(responseEntity.getContent()));

    int status = zdis.readInt();
    if (status == HttpURLConnection.HTTP_UNAUTHORIZED) {
        zdis.close();
        throw new IOException("Access denied. Check your username and password.");
    } else if (status <= 0 || status >= HttpURLConnection.HTTP_BAD_REQUEST) {
        zdis.close();
        throw new IOException(App.getApp().getString(R.string.error_connection));
    } else {
        assert (status == HttpURLConnection.HTTP_OK); // success
        return zdis;
    }
}