Example usage for org.apache.http.entity ContentType create

List of usage examples for org.apache.http.entity ContentType create

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType create.

Prototype

public static ContentType create(String str, String str2) throws UnsupportedCharsetException 

Source Link

Usage

From source file:com.neighbor.ex.tong.network.UploadFileAndMessage.java

@Override
protected Void doInBackground(Void... voids) {
    try {/*  w ww  . j  a va2s .c o  m*/

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addTextBody("message", URLEncoder.encode(message, "UTF-8"),
                ContentType.create("Multipart/related", "UTF-8"));
        builder.addPart("image", new FileBody(new File(path)));

        InputStream inputStream = null;
        HttpClient httpClient = AndroidHttpClient.newInstance("Android");

        String carNo = prefs.getString(CONST.ACCOUNT_LICENSE, "");
        String encodeCarNo = "";

        if (false == carNo.equals("")) {
            encodeCarNo = URLEncoder.encode(carNo, "UTF-8");
        }
        HttpPost httpPost = new HttpPost(UPLAOD_URL + encodeCarNo);
        httpPost.setEntity(builder.build());
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        inputStream = httpEntity.getContent();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;

        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line + "\n");
        }
        inputStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.autonomy.nonaci.indexing.impl.PostDataImpl.java

public PostDataImpl(final File file) {
    this(file, ContentType.create("text/plain", Charset.forName("UTF-8")));
}

From source file:org.nuxeo.elasticsearch.http.readonly.HttpClient.java

public static String get(String url, String payload) throws IOException {
    if (payload == null) {
        return get(url);
    }//from w  w w  . j  a  va2 s  .c  o  m
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGetWithEntity e = new HttpGetWithEntity(url);
    StringEntity myEntity = new StringEntity(payload,
            ContentType.create(MediaType.APPLICATION_FORM_URLENCODED, UTF8_CHARSET));
    e.setEntity(myEntity);
    try (CloseableHttpResponse response = client.execute(e)) {
        HttpEntity entity = response.getEntity();
        return entity != null ? EntityUtils.toString(entity) : null;
    }
}

From source file:org.mule.module.http.functional.listener.HttpListenerEncodingTestCase.java

@Test
public void testEncoding() throws Exception {
    final String url = String.format("http://localhost:%s/test", port.getNumber());
    Request request = Request.Post(url).bodyString(testMessage,
            ContentType.create("text/plain", Charset.forName(encoding)));
    request.execute();//w ww.java  2 s  .c  o m
    MuleMessage result = muleContext.getClient().request("vm://out", 2000);
    assertThat(result.getPayloadAsString(), is(testMessage));
}

From source file:com.infinities.keystone4j.PatchClient.java

public JsonNode connect(Object obj) throws ClientProtocolException, IOException {
    String input = JsonUtils.toJsonWithoutPrettyPrint(obj);
    logger.debug("input: {}", input);
    StringEntity requestEntity = new StringEntity(input, ContentType.create("application/json", Consts.UTF_8));

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from ww  w .  ja va 2s  .  c  o m
        HttpPatch request = new HttpPatch(url);
        request.addHeader("accept", "application/json");
        request.addHeader("X-Auth-Token", Config.Instance.getOpt(Config.Type.DEFAULT, "admin_token").asText());
        request.setEntity(requestEntity);
        ResponseHandler<JsonNode> rh = new ResponseHandler<JsonNode>() {

            @Override
            public JsonNode handleResponse(final HttpResponse response) throws IOException {
                StatusLine statusLine = response.getStatusLine();
                HttpEntity entity = response.getEntity();
                if (entity == null) {
                    throw new ClientProtocolException("Response contains no content");
                }
                String output = getStringFromInputStream(entity.getContent());
                logger.debug("output: {}", output);
                assertEquals(200, statusLine.getStatusCode());

                JsonNode node = JsonUtils.convertToJsonNode(output);
                return node;
            }

            private String getStringFromInputStream(InputStream is) {

                BufferedReader br = null;
                StringBuilder sb = new StringBuilder();

                String line;
                try {

                    br = new BufferedReader(new InputStreamReader(is));
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                return sb.toString();

            }
        };
        JsonNode node = httpclient.execute(request, rh);

        return node;
    } finally {
        httpclient.close();
    }
}

From source file:qhindex.servercomm.ServerDataCache.java

public JSONObject sendRequest(JSONObject data, String url, boolean sentAdminNotification) {
    JSONObject obj = new JSONObject();

    final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(AppHelper.connectionTimeOut)
            .setConnectionRequestTimeout(AppHelper.connectionTimeOut)
            .setSocketTimeout(AppHelper.connectionTimeOut).setStaleConnectionCheckEnabled(true).build();
    final CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
    HttpPost httpPost = new HttpPost(url);

    String dataStr = data.toJSONString();
    dataStr = dataStr.replaceAll("null", "\"\"");

    if (sentAdminNotification == true) {
        try {//from  w ww  . j a va 2 s  .c o  m
            AdminMail adminMail = new AdminMail();
            adminMail.sendMailToAdmin("Data to send to the server.", dataStr);
        } catch (Exception ex) { // Catch any problem during this step and continue 
            Debug.print("Could not send admin notification e-mail: " + ex);
        }
    }
    Debug.print("DATA REQUEST: " + dataStr);
    StringEntity jsonData = new StringEntity(dataStr, ContentType.create("plain/text", Consts.UTF_8));
    jsonData.setChunked(true);
    httpPost.addHeader("content-type", "application/json");
    httpPost.addHeader("accept", "application/json");
    httpPost.setEntity(jsonData);

    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() >= 300) {
            Debug.print("Exception while sending http request: " + statusLine.getStatusCode() + " : "
                    + statusLine.getReasonPhrase());
            resultsMsg += "Exception while sending http request: " + statusLine.getStatusCode() + " : "
                    + statusLine.getReasonPhrase() + "\n";
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String output = new String();
        String line;
        while ((line = br.readLine()) != null) {
            output += line;
        }
        output = output.substring(output.indexOf('{'));
        try {
            obj = (JSONObject) new JSONParser().parse(output);
        } catch (ParseException pEx) {
            Debug.print(
                    "Could not parse internet response. It is possible the cache server fail to deliver the content: "
                            + pEx.toString());
            resultsMsg += "Could not parse internet response. It is possible the cache server fail to deliver the content.\n";
        }
    } catch (IOException ioEx) {
        Debug.print("Could not handle the internet request: " + ioEx.toString());
        resultsMsg += "Could not handle the internet request.\n";
    }
    return obj;
}

From source file:juzu.impl.bridge.context.AbstractContextClientTestCase.java

protected void test(URL initialURL, String kind) throws Exception {
    driver.get(initialURL.toString());//from  w  w w  . j  av a2 s  .com
    WebElement link = driver.findElement(By.id(kind));
    contentLength = -1;
    charset = null;
    contentType = null;
    content = null;
    URL url = new URL(link.getAttribute("href"));

    DefaultHttpClient client = new DefaultHttpClient();
    // Little trick to force redirect after post
    client.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        protected boolean isRedirectable(String method) {
            return true;
        }
    });
    try {
        HttpPost post = new HttpPost(url.toURI());
        post.setEntity(new StringEntity("foo", ContentType.create("application/octet-stream", "UTF-8")));
        HttpResponse response = client.execute(post);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals(3, contentLength);
        assertEquals("UTF-8", charset);
        assertEquals("application/octet-stream; charset=UTF-8", contentType);
        assertEquals("foo", content);
        assertEquals(kind, AbstractContextClientTestCase.kind);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:betting.JsonEntity.java

/**
 * Constructs a new {@link JsonEntity} with the list of parameters in the
 * specified encoding./*from   w w w  .  ja v a  2 s.  c  om*/
 *
 * @param parameters
 *            list of name/value pairs
 * @param charset
 *            encoding the name/value pairs be encoded with
 * @throws UnsupportedEncodingException
 *             if the encoding isn't supported
 */
public JsonEntity(final List<? extends NameValuePair> parameters, final String charset)
        throws UnsupportedEncodingException {

    super(listToJson(parameters), ContentType.create(URLEncodedUtils.CONTENT_TYPE, charset));
}