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:com.fpmislata.productocategoriasjson.ProductoClienteTest.java

private static Producto updateProducto(String url, Producto producto) throws IOException {
    // Crea el producto para realizar la conexion
    DefaultHttpClient httpClient = new DefaultHttpClient();
    // Crea el mtodo con el que va a realizar la operacion
    HttpPut httpPut = new HttpPut(url);
    // Aade las cabeceras al metodo
    httpPut.addHeader("accept", "application/json; charset=UTF-8");
    httpPut.addHeader("Content-type", "application/json; charset=UTF-8");
    // Creamos el objeto Gson que parsear los objetos a JSON, excluyendo los que no tienen la anotacion @Expose
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    // Parseamos el objeto a String
    String jsonString = gson.toJson(producto);
    // Construimos el objeto StringEntity indicando que su juego de caracteres es UTF-8
    StringEntity input = new StringEntity(jsonString, "UTF-8");
    // Indicamos que su tipo MIME es JSON
    input.setContentType("application/json");
    // Asignamos la entidad al metodo con el que trabajamos
    httpPut.setEntity(input);
    // Invocamos el servicio rest y obtenemos la respuesta
    HttpResponse response = httpClient.execute(httpPut);

    // Comprobamos si ha fallado

    // Devolvemos el resultado
    String productoResult = readObject(response);
    return gson.fromJson(productoResult, Producto.class);
}

From source file:org.structr.android.restclient.StructrObject.java

private static int store(String path, StructrObject entity, Type type) throws Throwable {

    AndroidHttpClient httpClient = getHttpClient();
    HttpPut httpPut = new HttpPut(path);
    HttpResponse response = null;/*from   w ww.  j a  va2 s  . c  om*/
    Throwable throwable = null;
    int responseCode = 0;

    try {
        StringBuilder buf = new StringBuilder();
        gson.toJson(entity, type, buf);

        StringEntity body = new StringEntity(buf.toString());
        body.setContentType("application/json");
        httpPut.setEntity(body);
        configureRequest(httpPut);

        response = httpClient.execute(httpPut);
        responseCode = response.getStatusLine().getStatusCode();

    } catch (Throwable t) {
        throwable = t;
        httpPut.abort();
    } finally {
        if (response != null) {
            response.getEntity().consumeContent();
        }
    }

    if (throwable != null) {
        throw throwable;
    }

    return responseCode;
}

From source file:com.fpmislata.clientecategoriasjson.ClienteTest.java

private static Categoria updateCategoria(String url, Categoria categoria) throws IOException {
    // Crea el cliente para realizar la conexion
    DefaultHttpClient httpClient = new DefaultHttpClient();
    // Crea el mtodo con el que va a realizar la operacion
    HttpPut httpPut = new HttpPut(url);
    // Aade las cabeceras al metodo
    httpPut.addHeader("accept", "application/json; charset=UTF-8");
    httpPut.addHeader("Content-type", "application/json; charset=UTF-8");
    // Creamos el objeto Gson que parsear los objetos a JSON, excluyendo los que no tienen la anotacion @Expose
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    // Parseamos el objeto a String
    String jsonString = gson.toJson(categoria);
    // Construimos el objeto StringEntity indicando que su juego de caracteres es UTF-8
    StringEntity input = new StringEntity(jsonString, "UTF-8");
    // Indicamos que su tipo MIME es JSON
    input.setContentType("application/json");
    // Asignamos la entidad al metodo con el que trabajamos
    httpPut.setEntity(input);
    // Invocamos el servicio rest y obtenemos la respuesta
    HttpResponse response = httpClient.execute(httpPut);

    // Comprobamos si ha fallado
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    } else {/*  w  ww  .j  av  a2  s.  c  o  m*/
        System.out.println("La actualizacin ha ido correcta.");
    }

    // Devolvemos el resultado
    String categoriaResult = readObject(response);
    return gson.fromJson(categoriaResult, Categoria.class);
}

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

public void xputElastic(String index, String type, String ID, File f) throws Exception {

    DefaultHttpClient httpClient = new DefaultHttpClient();
    String url = "http://localhost:9200/" + index + "/" + type + "/" + ID;
    System.out.println(url);/*from ww  w.  j a  va  2  s  . c  om*/
    HttpPut put = new HttpPut(url); //-X PUT
    put.setEntity(new FileEntity(f, "application/json")); //@ - absolute path
    BasicResponseHandler responseHandler = new BasicResponseHandler();

    String o = httpClient.execute(put, responseHandler);
    /* System.err.println("----------"+o+"----------");
     if(o == null || o.trim().length() == 0)
     {
         System.err.println(o);
         System.exit(1);
     } */

}

From source file:org.apache.cloudstack.storage.datastore.util.DateraUtil.java

public static String login(DateraObject.DateraConnection conn)
        throws UnsupportedEncodingException, DateraObject.DateraError {

    DateraObject.DateraLogin loginParams = new DateraObject.DateraLogin(conn.getUsername(), conn.getPassword());
    HttpPut loginReq = new HttpPut(generateApiUrl("login"));

    StringEntity jsonParams = new StringEntity(gson.toJson(loginParams));
    loginReq.setEntity(jsonParams);

    String response = executeHttp(conn, loginReq);
    DateraObject.DateraLoginResponse loginResponse = gson.fromJson(response,
            DateraObject.DateraLoginResponse.class);

    return loginResponse.getKey();

}

From source file:io.crate.integrationtests.BlobHttpClient.java

public CloseableHttpResponse put(String table, String body) throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    String digest = Hex.encodeHexString(Blobs.digest(body));
    String url = Blobs.url(address, table + "/" + digest);
    HttpPut httpPut = new HttpPut(url);
    httpPut.setEntity(new StringEntity(body));
    return httpClient.execute(httpPut);
}

From source file:ca.uhn.fhir.rest.method.HttpPutClientInvocation.java

@Override
protected HttpRequestBase createRequest(StringBuilder theUrl, AbstractHttpEntity theEntity) {
    HttpPut retVal = new HttpPut(theUrl.toString());
    retVal.setEntity(theEntity);
    return retVal;
}

From source file:com.meschbach.psi.util.rest.PutRequest.java

@Override
protected HttpUriRequest build(URI resource, HttpEntity entity) {
    HttpPut put = new HttpPut(resource);
    put.setEntity(entity);
    return put;//from   w w w.  j  a  v  a  2 s. co  m
}

From source file:org.apache.manifoldcf.agents.output.opensearchserver.OpenSearchServerScheduler.java

public OpenSearchServerScheduler(HttpClient client, OpenSearchServerConfig config, String schedulerName)
        throws ManifoldCFException {
    super(client, config);
    String path = StringUtils.replace(PATH, "{index_name}", URLEncoder.encode(config.getIndexName()));
    path = StringUtils.replace(path, "{scheduler_name}", URLEncoder.encode(schedulerName));
    StringBuffer url = getApiUrlV2(path);
    HttpPut put = new HttpPut(url.toString());
    put.setEntity(new StringEntity("{}", ContentType.APPLICATION_JSON));
    call(put);/*  w  w w. j  ava  2 s.  c om*/
}

From source file:org.talend.dataprep.api.service.command.folder.RenameFolder.java

private HttpRequestBase onExecute(final String id, final String newName) {
    try {/*from   w ww .ja  v  a 2 s . com*/
        final URIBuilder uriBuilder = new URIBuilder(preparationServiceUrl + "/folders/" + id + "/name");
        uriBuilder.addParameter("newName", newName);
        final HttpPut put = new HttpPut(uriBuilder.build());
        put.setEntity(new StringEntity(newName));
        return put;
    } catch (UnsupportedEncodingException | URISyntaxException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }
}