Example usage for org.apache.http.entity StringEntity setContentType

List of usage examples for org.apache.http.entity StringEntity setContentType

Introduction

In this page you can find the example usage for org.apache.http.entity StringEntity setContentType.

Prototype

public void setContentType(Header header) 

Source Link

Usage

From source file:com.fpmislata.productocategoriasjson.ProductoClienteTest.java

private static Producto addProducto(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
    HttpPost httpPost = new HttpPost(url);
    // Aade las cabeceras al metodo
    httpPost.addHeader("accept", "application/json; charset=UTF-8");
    httpPost.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
    httpPost.setEntity(input);/*from w w  w .  j a v  a2  s . c  om*/
    // Invocamos el servicio rest y obtenemos la respuesta
    HttpResponse response = httpClient.execute(httpPost);

    // Comprobamos si ha fallado
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }

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

From source file:org.sensapp.android.sensappdroid.restrequests.RestRequest.java

public static String putData(Uri uri, String data) throws RequestErrorException {
    URI target;// w  ww .  j  a  va 2 s .c  o  m
    try {
        target = new URI(uri.toString() + DISPATCHER_PATH);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        throw new RequestErrorException(e1.getMessage());
    }
    HttpClient client = new DefaultHttpClient();
    HttpPut request = new HttpPut(target);
    request.setHeader("Content-type", "application/json");
    String response = null;
    try {
        StringEntity seContent = new StringEntity(data);
        seContent.setContentType("text/json");
        request.setEntity(seContent);
        response = resolveResponse(client.execute(request));
    } catch (Exception e) {
        throw new RequestErrorException(e.getMessage());
    }
    if (response.trim().length() > 2) {
        throw new RequestErrorException("Sensor not registred: " + response);
    }
    return response;
}

From source file:v2.service.generic.library.utils.HttpClientUtil.java

public static HttpResponsePOJO jsonRequest(String url, String json, String requestType,
        Map<String, String> headers) throws Exception {
    HttpClient httpclient = createHttpClient();
    //        HttpEntityEnclosingRequestBase request=null;
    HttpRequestBase request = null;/*from  w  ww .  j  a v a  2 s.co  m*/
    if ("POST".equalsIgnoreCase(requestType)) {
        request = new HttpPost(url);
    } else if ("PUT".equalsIgnoreCase(requestType)) {
        request = new HttpPut(url);
    } else if ("GET".equalsIgnoreCase(requestType)) {
        request = new HttpGet(url);
    } else if ("DELETE".equalsIgnoreCase(requestType)) {
        request = new HttpDelete(url);
    }
    if (json != null) {
        if (!"GET".equalsIgnoreCase(requestType) && (!"DELETE".equalsIgnoreCase(requestType))) {
            StringEntity params = new StringEntity(json, "UTF-8");
            params.setContentType("application/json;charset=UTF-8");
            ((HttpEntityEnclosingRequestBase) request).setEntity(params);
        }
    }
    if (headers == null) {
        request.addHeader("content-type", "application/json");
    } else {
        Set<String> keySet_header = headers.keySet();
        for (String key : keySet_header) {
            request.setHeader(key, headers.get(key));
        }
    }
    HttpResponsePOJO result = invoke(httpclient, request);
    return result;
}

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

private static Cliente addCliente(String url, Cliente cliente) throws IOException {
    // Crea el cliente para realizar la conexion
    DefaultHttpClient httpClient = new DefaultHttpClient();
    // Crea el mtodo con el que va a realizar la operacion
    HttpPost httpPost = new HttpPost(url);
    // Aade las cabeceras al metodo
    httpPost.addHeader("accept", "application/json; charset=UTF-8");
    httpPost.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(cliente);
    // 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
    httpPost.setEntity(input);//from   w ww  . j  ava  2 s. co m
    // Invocamos el servicio rest y obtenemos la respuesta
    HttpResponse response = httpClient.execute(httpPost);

    // Comprobamos si ha fallado
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }

    String clienteResult = readObject(response);
    return gson.fromJson(clienteResult, Cliente.class);
}

From source file:org.sensapp.android.sensappdroid.restrequests.RestRequest.java

public static String postComposite(Composite composite) throws RequestErrorException {
    String content = JsonPrinter.compositeToJson(composite);
    URI target;/* w  w  w  .  j  ava2  s.  c  om*/
    try {
        target = new URI(composite.getUri().toString() + COMPOSITE_PATH);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        throw new RequestErrorException(e1.getMessage());
    }
    HttpClient client = new DefaultHttpClient();
    HttpPost request = new HttpPost(target);
    request.setHeader("Content-type", "application/json");
    String response = null;
    try {
        StringEntity seContent = new StringEntity(content);
        seContent.setContentType("text/json");
        request.setEntity(seContent);
        response = resolveResponse(client.execute(request));
    } catch (Exception e) {
        throw new RequestErrorException(e.getMessage());
    }
    return response;
}

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

private static Categoria addCategoria(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
    HttpPost httpPost = new HttpPost(url);
    // Aade las cabeceras al metodo
    httpPost.addHeader("accept", "application/json; charset=UTF-8");
    httpPost.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
    httpPost.setEntity(input);/* w w  w .  ja  v  a  2  s.  c om*/
    // Invocamos el servicio rest y obtenemos la respuesta
    HttpResponse response = httpClient.execute(httpPost);

    // Comprobamos si ha fallado
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }

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

From source file:com.networknt.light.server.handler.loader.PageLoader.java

private static void loadPageFile(String host, File file) {
    Scanner scan = null;/*w w w . j  av a2 s  . c  om*/
    try {
        scan = new Scanner(file, Loader.encoding);
        // the content is only the data portion. convert to map
        String content = scan.useDelimiter("\\Z").next();
        String pageId = file.getName();
        pageId = pageId.substring(0, pageId.lastIndexOf('.'));
        if (content != null && !content.equals(pageMap.get(pageId))) {
            System.out.println(content);
            System.out.println(pageMap.get(pageId));
            Map<String, Object> inputMap = new HashMap<String, Object>();
            inputMap.put("category", "page");
            inputMap.put("name", "impPage");
            inputMap.put("readOnly", false);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("pageId", pageId);
            data.put("content", content);
            inputMap.put("data", data);
            HttpPost httpPost = new HttpPost(host + "/api/rs");
            httpPost.addHeader("Authorization", "Bearer " + jwt);
            StringEntity input = new StringEntity(
                    ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap));
            input.setContentType("application/json");
            httpPost.setEntity(input);
            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                System.out.println("Page: " + file.getAbsolutePath() + " is loaded with status "
                        + response.getStatusLine());
                HttpEntity entity = response.getEntity();
                BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
                String json = "";
                String line = "";
                while ((line = rd.readLine()) != null) {
                    json = json + line;
                }
                //System.out.println("json = " + json);
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } else {
            //System.out.println("Skip file " + pageId);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (scan != null)
            scan.close();
    }
}

From source file:org.openo.nfvo.monitor.dac.util.APIHttpClient.java

@SuppressWarnings({ "resource" })
public static String doPost2Str(String url, JSONObject json, String token) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    String response = null;/*from  w ww.  j  a  v a2s  .  c  o m*/
    try {
        if (null != json) {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json"); // set contentType
            post.setEntity(s);
        }
        if (!Global.isEmpty(token)) {
            post.addHeader("X-Auth-Token", token);
        }
        HttpResponse res = client.execute(post);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                || res.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            String result = EntityUtils.toString(res.getEntity());
            logger.info("post result is :{}", result);
            if (!Global.isEmpty(result)) {
                response = result;
            } else {
                response = null;
            }
        }
    } catch (Exception e) {
        logger.error("Exception", e);
    }
    return response;
}

From source file:org.openo.nfvo.monitor.dac.util.APIHttpClient.java

@SuppressWarnings({ "resource" })
public static JSONObject doPost(String url, JSONObject json, String token) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    JSONObject response = null;/*www  .java  2 s .  c  om*/
    try {
        if (null != json) {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);
        }
        if (!Global.isEmpty(token)) {
            post.addHeader("X-Auth-Token", token);
        }
        HttpResponse res = client.execute(post);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                || res.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            String result = EntityUtils.toString(res.getEntity());
            logger.info("post result is :{}", result);
            if (!Global.isEmpty(result)) {
                response = JSONObject.fromObject(result);
            } else {
                response = null;
            }
        }
    } catch (Exception e) {
        logger.error("Exception", e);
    }
    return response;
}

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);//from  w ww.  j  a va  2  s .  c o  m
    // 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 {
        System.out.println("La actualizacin ha ido correcta.");
    }

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