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:io.openkit.OKHTTPClient.java

private static StringEntity getJSONString(JSONObject jsonObject) {
    StringEntity sEntity = null;
    try {/*from www  .j  a v a  2s.  c o  m*/
        sEntity = new StringEntity(jsonObject.toString(), HTTP.UTF_8);
        sEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        return sEntity;
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}

From source file:cn.hi321.browser.weave.client.WeaveUtil.java

@SuppressWarnings("unused")
private static HttpEntity toHttpEntity(JSONArray jsonArray) throws JSONException {
    try {/*w w w.  j  av  a 2  s .c  om*/
        StringEntity entity = new StringEntity(jsonArray.toString(0), ENTITY_CHARSET_NAME);
        entity.setContentType(JSON_STREAM_TYPE + HTTP.CHARSET_PARAM + ENTITY_CHARSET_NAME);
        return entity;
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
    }
}

From source file:cn.hi321.browser.weave.client.WeaveUtil.java

@SuppressWarnings("unused")
private static HttpEntity toHttpEntity(WeaveBasicObject wbo) throws JSONException {
    try {//from w  w w . j a  v a2  s .c  om
        StringEntity entity = new StringEntity(wbo.toJSONObjectString(), ENTITY_CHARSET_NAME);
        entity.setContentType(JSON_STREAM_TYPE + HTTP.CHARSET_PARAM + ENTITY_CHARSET_NAME);
        return entity;
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
    }
}

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

/**
 * Get all pages from the server and construct a map in order to compare content
 * to detect changes or not./*  w w  w  .  j  a va 2 s  .  com*/
 *
 */
private static void getPageMap(String host) {

    Map<String, Object> inputMap = new HashMap<String, Object>();
    inputMap.put("category", "page");
    inputMap.put("name", "getPageMap");
    inputMap.put("readOnly", true);

    CloseableHttpResponse response = null;
    try {
        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);
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
        String json = "";
        String line = "";
        while ((line = rd.readLine()) != null) {
            json = json + line;
        }
        EntityUtils.consume(entity);
        System.out.println("Got page map from server");
        if (json != null && json.trim().length() > 0) {
            pageMap = ServiceLocator.getInstance().getMapper().readValue(json,
                    new TypeReference<HashMap<String, String>>() {
                    });
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:net.modelbased.proasense.storage.registry.RestRequest.java

public static String putData(URI uri, String data) {
    URI target = null;//www  .  j ava 2 s  . c  o m
    try {
        target = new URI(uri.toString() + DISPATCHER_PATH);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    }
    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) {
        e.printStackTrace();
    }
    if (response.trim().length() > 2) {
        throw new IllegalAccessError("Sensor not registred: " + response);
    }
    return response;
}

From source file:net.modelbased.proasense.storage.registry.RestRequest.java

public static String postSensor(Sensor sensor) {
    String content = JsonPrinter.sensorToJson(sensor);
    URI target = null;/*w w  w.ja va2s .c o  m*/
    try {
        target = new URI(sensor.getUri().toString() + SENSOR_PATH);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    }
    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) {
        e.printStackTrace();
    }
    return response;
}

From source file:net.modelbased.proasense.storage.registry.RestRequest.java

public static String postComposite(Composite composite) {
    String content = JsonPrinter.compositeToJson(composite);
    URI target = null;/* w w w .ja va2s .co  m*/
    try {
        target = new URI(composite.getUri().toString() + COMPOSITE_PATH);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    }
    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) {
        e.printStackTrace();
    }
    return response;
}

From source file:org.dhis.smssync.net.MainHttpClient.java

/**
 * Upload SMS to a web service via HTTP POST
 * //from w  w  w.j a v  a  2 s  .  c o  m
 * @param address
 * @throws MalformedURLException
 * @throws IOException
 * @return
 */
public static boolean postSmsToWebService(String url, String xml, Context context) {

    Prefrences.loadPreferences(context);
    String encoding = Prefrences.dhisLoginPref;

    // Create a new HttpClient and Post Header
    HttpPost httppost = new HttpPost(url);
    httppost.setHeader("Authorization", "Basic " + encoding);

    try {
        StringEntity se = new StringEntity(xml, HTTP.UTF_8);

        se.setContentType("application/xml");
        httppost.setEntity(se);

        BasicHttpResponse response = (BasicHttpResponse) httpclient.execute(httppost);

        Log.i(CLASS_TAG, "postSmsToWebService(): code: " + response.getStatusLine().getStatusCode() + " xml: "
                + xml + " encoding: " + encoding);

        if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300) {
            return true;
        } else {
            return false;
        }

    } catch (ClientProtocolException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
}

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);/*w  ww.ja  v  a2 s .  com*/
    // 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:com.fpmislata.clientecategoriasjson.ClienteClienteTest.java

private static Cliente updateCliente(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
    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(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
    httpPut.setEntity(input);/*  ww w .  j  a v  a2  s.  c om*/
    // Invocamos el servicio rest y obtenemos la respuesta
    HttpResponse response = httpClient.execute(httpPut);

    // Comprobamos si ha fallado

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