Example usage for org.apache.http.client.methods HttpPut setEntity

List of usage examples for org.apache.http.client.methods HttpPut setEntity

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPut setEntity.

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:edu.ucsd.ccdb.cil.xml2json.ElasticsearchClient.java

public static void main(String[] args) throws Exception {
    try {// ww  w .j  a  v  a 2 s.co m
        DefaultHttpClient httpClient = new DefaultHttpClient();

        //HttpPut put = new HttpPut("http://localhost:9200/customer/user/john@smith.com");  //-X PUT
        //put.setEntity(new FileEntity(new File("/Users/ncmir/NetBeansProjects/MyTest/web/customer.json"), "application/json"));  //@ - absolute path
        HttpPut put = new HttpPut("http://localhost:9200/ccdb/data/1"); //-X PUT
        put.setEntity(
                new FileEntity(new File("/Users/ncmir/Documents/CCDB/ccdbJson/1.json"), "application/json")); //@ - absolute path

        BasicResponseHandler responseHandler = new BasicResponseHandler();

        String o = httpClient.execute(put, responseHandler);
        System.out.println(o);
    } catch (Exception e) {
        //-f, fail silently
        e.printStackTrace();
    }
}

From source file:web.restful.ClientTest.java

public static void main(String[] args) throws ClientProtocolException, IOException {
    HttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut("http://localhost:8080/ss16-lab-web/resources/outliers/session");
    put.setEntity(new StringEntity("upenkwbq"));// session ID
    client.execute(put);/*w  w w.ja  va 2  s  . c o m*/
    put.releaseConnection();

    put = new HttpPut("http://localhost:8080/ss16-lab-web/resources/outliers/bucket");
    put.setEntity(new StringEntity("Level1/Level1_Bin_1.txt")); // bucket name
    client.execute(put);
    put.releaseConnection();

    put = new HttpPut("http://localhost:8080/ss16-lab-web/resources/outliers/method");
    put.setEntity(new StringEntity("chauvenet")); // method name
    client.execute(put);
    put.releaseConnection();

    HttpGet get = new HttpGet("http://localhost:8080/ss16-lab-web/resources/outliers");
    HttpResponse response = client.execute(get);
    HttpEntity en = response.getEntity();
    InputStreamReader i = new InputStreamReader(en.getContent());
    BufferedReader rd = new BufferedReader(i);
    String line = "";
    while ((line = rd.readLine()) != null) {
        System.out.println(line);
    }
}

From source file:com.javaquery.apache.httpclient.HttpPutExample.java

public static void main(String[] args) {
    /* Create object of CloseableHttpClient */
    CloseableHttpClient httpClient = HttpClients.createDefault();

    /* Prepare put request */
    HttpPut httpPut = new HttpPut("http://www.example.com/api/customer");
    /* Add headers to get request */
    httpPut.addHeader("Authorization", "value");

    /* Prepare StringEntity from JSON */
    StringEntity jsonData = new StringEntity("{\"id\":\"123\", \"name\":\"Vicky Thakor\"}", "UTF-8");
    /* Body of request */
    httpPut.setEntity(jsonData);

    /* Response handler for after request execution */
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        @Override/*from   www . jav a  2  s  .c  o  m*/
        public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
            /* Get status code */
            int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println("Response code: " + httpResponseCode);
            if (httpResponseCode >= 200 && httpResponseCode < 300) {
                /* Convert response to String */
                HttpEntity entity = httpResponse.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                return null;
                /* throw new ClientProtocolException("Unexpected response status: " + httpResponseCode); */
            }
        }
    };

    try {
        /* Execute URL and attach after execution response handler */
        String strResponse = httpClient.execute(httpPut, responseHandler);
        /* Print the response */
        System.out.println("Response: " + strResponse);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.imaginary.home.cloud.api.call.LocationCall.java

static public void main(String... args) throws Exception {
    if (args.length < 1) {
        System.err.println("You must specify an action");
        System.exit(-1);/*from  ww  w . ja  va2  s . c o m*/
        return;
    }
    String action = args[0];

    if (action.equalsIgnoreCase("initializePairing")) {
        if (args.length < 5) {
            System.err.println("You must specify a location ID");
            System.exit(-2);
            return;
        }
        String endpoint = args[1];
        String locationId = args[2];
        String apiKeyId = args[3];
        String apiKeySecret = args[4];

        HashMap<String, Object> act = new HashMap<String, Object>();

        act.put("action", "initializePairing");

        HttpParams params = new BasicHttpParams();

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        //noinspection deprecation
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpProtocolParams.setUserAgent(params, "Imaginary Home");

        HttpClient client = new DefaultHttpClient(params);

        HttpPut method = new HttpPut(endpoint + "/location/" + locationId);
        long timestamp = System.currentTimeMillis();

        method.addHeader("Content-Type", "application/json");
        method.addHeader("x-imaginary-version", CloudService.VERSION);
        method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp));
        method.addHeader("x-imaginary-api-key", apiKeyId);
        method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"),
                "put:/location/" + locationId + ":" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION));

        //noinspection deprecation
        method.setEntity(new StringEntity((new JSONObject(act)).toString(), "application/json", "UTF-8"));

        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(method);
            status = response.getStatusLine();
        } catch (IOException e) {
            e.printStackTrace();
            throw new CommunicationException(e);
        }
        if (status.getStatusCode() == HttpServletResponse.SC_OK) {
            String json = EntityUtils.toString(response.getEntity());
            JSONObject u = new JSONObject(json);

            System.out.println((u.has("pairingCode") && !u.isNull("pairingCode")) ? u.getString("pairingCode")
                    : "--no code--");
        } else {
            System.err.println("Failed to initialize pairing  (" + status.getStatusCode() + ": "
                    + EntityUtils.toString(response.getEntity()));
            System.exit(status.getStatusCode());
        }
    } else if (action.equalsIgnoreCase("create")) {
        if (args.length < 7) {
            System.err.println("create ENDPOINT NAME DESCRIPTION TIMEZONE API_KEY_ID API_KEY_SECRET");
            System.exit(-2);
            return;
        }
        String endpoint = args[1];
        String name = args[2];
        String description = args[3];
        String tz = args[4];
        String apiKeyId = args[5];
        String apiKeySecret = args[6];

        HashMap<String, Object> lstate = new HashMap<String, Object>();

        lstate.put("name", name);
        lstate.put("description", description);
        lstate.put("timeZone", tz);

        HttpParams params = new BasicHttpParams();

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        //noinspection deprecation
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpProtocolParams.setUserAgent(params, "Imaginary Home");

        HttpClient client = new DefaultHttpClient(params);

        HttpPost method = new HttpPost(endpoint + "/location");
        long timestamp = System.currentTimeMillis();

        System.out.println(
                "Signing: " + "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION);
        method.addHeader("Content-Type", "application/json");
        method.addHeader("x-imaginary-version", CloudService.VERSION);
        method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp));
        method.addHeader("x-imaginary-api-key", apiKeyId);
        method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"),
                "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION));

        //noinspection deprecation
        method.setEntity(new StringEntity((new JSONObject(lstate)).toString(), "application/json", "UTF-8"));

        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(method);
            status = response.getStatusLine();
        } catch (IOException e) {
            e.printStackTrace();
            throw new CommunicationException(e);
        }
        if (status.getStatusCode() == HttpServletResponse.SC_CREATED) {
            String json = EntityUtils.toString(response.getEntity());
            JSONObject u = new JSONObject(json);

            System.out.println((u.has("locationId") && !u.isNull("locationId")) ? u.getString("locationId")
                    : "--no location--");
        } else {
            System.err.println("Failed to create location  (" + status.getStatusCode() + ": "
                    + EntityUtils.toString(response.getEntity()));
            System.exit(status.getStatusCode());
        }
    } else {
        System.err.println("No such action: " + action);
        System.exit(-3);
    }
}

From source file:org.jboss.pnc.mavenrepositorymanager.ArtifactUploadUtils.java

public static boolean put(CloseableHttpClient client, String url, String content) throws IOException {
    HttpPut put = new HttpPut(url);
    put.setEntity(new StringEntity(content));
    return client.execute(put, response -> {
        try {//  w  w  w.  j  a v a2 s.c  o  m
            return response.getStatusLine().getStatusCode() == 201;
        } finally {
            if (response instanceof CloseableHttpResponse) {
                IOUtils.closeQuietly((CloseableHttpResponse) response);
            }
        }
    });
}

From source file:com.vmware.content.samples.client.util.HttpUtil.java

/**
 * Uploads a file from local storage to a given HTTP URI.
 *
 * @param localFile local storage path to the file to upload.
 * @param uploadUri HTTP URI where the file needs to be uploaded.
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.KeyStoreException
 * @throws java.security.KeyManagementException
 * @throws java.io.IOException//from  w w  w . j  a  v  a  2s .c  o m
 */
public static void uploadFileToUri(File localFile, URI uploadUri)
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
    CloseableHttpClient httpClient = getCloseableHttpClient();
    HttpPut request = new HttpPut(uploadUri);
    HttpEntity content = new FileEntity(localFile);
    request.setEntity(content);
    HttpResponse response = httpClient.execute(request);
    EntityUtils.consumeQuietly(response.getEntity());
}

From source file:com.google.android.gcm.demo.app.utils.ServerUtilities.java

/**
 * Issue a POST request to the server.//from  ww w  .j ava  2  s . c o m
 *
 * @param endpoint POST address.
 * @param json     object to send.
 * @throws IOException propagated from PUT.
 */
private static HttpResponse doHttpPut(String endpoint, JSONObject json) throws IOException {
    HttpPut putRequest = new HttpPut(endpoint);
    putRequest.setEntity(new StringEntity(json.toString()));
    putRequest.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    return executeRequest(putRequest);
}

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

protected static HttpPut putDSMethod(final String pid, final String ds, final String content)
        throws UnsupportedEncodingException {
    final HttpPut put = new HttpPut(serverAddress + pid + "/" + ds + "/jcr:content");

    put.setEntity(new StringEntity(content));
    return put;/*from  w  w w .  j  a va2  s  . co m*/
}

From source file:com.github.rnewson.couchdb.lucene.couchdb.HttpUtils.java

public static final int put(final HttpClient httpClient, final String url, final String body)
        throws IOException {
    final HttpPut put = new HttpPut(url);
    if (body != null) {
        put.setHeader("Content-Type", Constants.APPLICATION_JSON);
        put.setEntity(new StringEntity(body, "UTF-8"));
    }//w w  w.j a  v a 2 s  .co  m
    return httpClient.execute(put, new StatusCodeResponseHandler());
}

From source file:org.fcrepo.auth.oauth.integration.api.AbstractOAuthResourceIT.java

protected static HttpPut putDSMethod(final String pid, final String ds, final String content)
        throws UnsupportedEncodingException {
    final HttpPut put = new HttpPut(serverAddress + "objects/" + pid + "/" + ds + "/fcr:content");

    put.setEntity(new StringEntity(content));
    return put;/*from  w  ww .  j  a v  a  2 s  .  c  o  m*/
}