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:org.dashbuilder.dataprovider.backend.elasticsearch.ElasticSearchDataSetTestBase.java

/**
 * <p>Index a single document into EL server.</p>
 *//*from  w  w w  . java  2  s.  c  om*/
protected static void addDocument(CloseableHttpClient httpclient, String type, String document)
        throws Exception {
    HttpPost httpPut = new HttpPost(urlBuilder.getIndexRoot() + "/" + type);
    StringEntity inputData = new StringEntity(document);
    inputData.setContentType(CONTENTTYPE_JSON);
    httpPut.addHeader(HEADER_ACCEPT, CONTENTTYPE_JSON);
    httpPut.addHeader(HEADER_CONTENTTYPE, CONTENTTYPE_JSON);
    httpPut.setEntity(inputData);
    CloseableHttpResponse dataResponse = httpclient.execute(httpPut);
    if (dataResponse.getStatusLine().getStatusCode() != EL_REST_RESPONSE_CREATED) {
        System.out.println("Error response body:");
        System.out.println(responseAsString(dataResponse));
    }
    Assert.assertEquals(dataResponse.getStatusLine().getStatusCode(), EL_REST_RESPONSE_CREATED);
}

From source file:com.mywork.framework.util.RemoteHttpUtil.java

/**
 * ?? Post//from   www  . j av a  2 s.  c  o  m
 * @return
 */
public static String doPost(String contentUrl, Map<String, String> headerMap, String jsonBody) {
    String result = null;
    CloseableHttpResponse response = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost post = new HttpPost(contentUrl);
    RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT_SECONDS * 1000)
            .setConnectTimeout(TIMEOUT_SECONDS * 1000).setSocketTimeout(TIMEOUT_SECONDS * 1000).build();
    post.setConfig(config);

    try {
        if (headerMap != null && !headerMap.isEmpty()) {
            for (Map.Entry<String, String> m : headerMap.entrySet()) {
                post.setHeader(m.getKey(), m.getValue());
            }
        }

        if (jsonBody != null) {
            StringEntity entity = new StringEntity(jsonBody, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            post.setEntity(entity);
        }
        long start = System.currentTimeMillis();
        response = httpClient.execute(post);
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        logger.info("url = " + contentUrl + " request spend time = " + (System.currentTimeMillis() - start));
        EntityUtils.consume(entity);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return result;
}

From source file:org.dashbuilder.dataprovider.backend.elasticsearch.ElasticSearchDataSetTestBase.java

public static void createIndexELServer() throws Exception {

    // Create an http client
    CloseableHttpClient httpclient = HttpClients.createDefault();

    // Obtain data to configure & populate the server.
    String mappingsContent = getFileAsString(EL_EXAMPLE_MAPPINGS);

    // Create an index mappings.
    HttpPost httpPost = new HttpPost(urlBuilder.getIndexRoot());
    StringEntity inputMappings = new StringEntity(mappingsContent);
    inputMappings.setContentType(CONTENTTYPE_JSON);
    httpPost.setEntity(inputMappings);/*from   ww w  .  j  av a2  s .c  o  m*/
    CloseableHttpResponse mappingsResponse = httpclient.execute(httpPost);
    if (mappingsResponse.getStatusLine().getStatusCode() != EL_REST_RESPONSE_OK) {
        System.out.println("Error response body:");
        System.out.println(responseAsString(mappingsResponse));
    }
    Assert.assertEquals(EL_REST_RESPONSE_OK, mappingsResponse.getStatusLine().getStatusCode());
}

From source file:org.apache.gobblin.service.modules.orchestration.AzkabanAjaxAPIClient.java

private static HttpPost preparePostRequest(String requestUrl, String sessionId, Map<String, String> params)
        throws IOException {
    // Create post request
    HttpPost postRequest = new HttpPost(requestUrl);
    StringBuilder stringEntityBuilder = new StringBuilder();
    stringEntityBuilder.append(String.format("session.id=%s", sessionId));
    for (Map.Entry<String, String> entry : params.entrySet()) {
        if (stringEntityBuilder.length() > 0) {
            stringEntityBuilder.append("&");
        }/*  w  w w . j av  a 2 s  . co  m*/
        stringEntityBuilder.append(String.format("%s=%s", entry.getKey(), entry.getValue()));
    }
    StringEntity input = new StringEntity(stringEntityBuilder.toString());
    input.setContentType("application/x-www-form-urlencoded");
    postRequest.setEntity(input);
    postRequest.setHeader("X-Requested-With", "XMLHttpRequest");

    return postRequest;
}

From source file:org.frameworkset.spi.remote.http.Client.java

public static RPCMessage sendMessage(RPCMessage srcmessag, RPCAddress address)
        throws ClientProtocolException, Exception {
    // InetSocketAddress serverAddress = new
    // InetSocketAddress("172.16.17.216",8080);
    // for(int i = 0; i < 10; i ++)
    // {//  w w  w  . j  a v  a  2s  . c o m
    //      
    // // Obtain HTTP connection
    // this.client.openConnection(
    // serverAddress,
    // "duoduo");
    // }
    HttpResponse response = null;
    HttpClient httpclient = null;
    HttpPost httppost = null;
    try {
        //         httpclient = buildHttpClient(address);
        httpclient = buildHttpClient_(address);
        //         httpclient.getParams().setParameter(HttpConnectionParams, arg1);
        String address_real = TargetImpl.buildWebserviceURL(address);
        httppost = new HttpPost(address_real);

        //         XStream stream_ = new XStream();
        String message_ = ObjectSerializable.toXML(srcmessag);
        //         System.out.println(message_);
        StringEntity reqEntity = new StringEntity(message_, BBossHttp.UTF_8);
        reqEntity.setContentType(BBossHttp.XML_TEXT_TYPE);

        httppost.setEntity(reqEntity);
        httppost.setParams(params);

        log.debug("executing request " + httppost.getRequestLine());
        response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() != 200) {
            StringBuffer message = new StringBuffer();
            message.append(response.getStatusLine() + "\r\n");
            message.append(EntityUtils.toString(response.getEntity()));

            throw new HttpRuntimeException(message.toString());
        }
        HttpEntity entity = response.getEntity();

        //         System.out.println("----------------------------------------");
        //         System.out.println(response.getStatusLine());
        //         if (entity != null) {
        //            System.out.println("Response content length: "
        //                  + entity.getContentLength());
        //            System.out.println("Chunked?: " + entity.isChunked());
        //         }

        if (entity != null) {
            try {
                // ObjectInputStream in = new
                // ObjectInputStream(entity.getContent());
                InputStream instream = entity.getContent();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                //               String xml = getFileContent( instream,"UTF-8");
                //               System.out.println(xml);

                //               XStream stream = new XStream();
                RPCMessage bean = (RPCMessage) ObjectSerializable.toBean(instream, RPCMessage.class);
                // System.out.println(bean.getId());
                // System.out.println(bean.getName());
                // System.out.println(in.readInt());
                // System.out.println(in.readObject());
                return bean;

            } catch (IOException e) {
                e.printStackTrace();
                throw e;
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }

            // catch (ClassNotFoundException e) {
            // // TODO Auto-generated catch block
            // e.printStackTrace();
            // }
        } else {
            throw new Exception("Result is null.");

        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (usepool) {
            if (httppost != null) {
                try {
                    httppost.abort();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (!usepool) {
            //            shutdownclient(httpclient);
            try {
                httppost.abort();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources

}

From source file:co.aurasphere.botmill.fb.internal.util.network.FbBotMillNetworkController.java

/**
 * Utility method that converts an object to its StringEntity
 * representation./*  w  w w  .j a  v  a 2 s.  c  o  m*/
 * 
 * @param object
 *            the object to convert to a StringEntity.
 * @return a {@link StringEntity} object containing the object JSON.
 */
private static StringEntity toStringEntity(Object object) {
    StringEntity input = null;
    try {
        String json = FbBotMillJsonUtils.toJson(object);
        input = new StringEntity(json, "UTF-8");
        input.setContentType("application/json");
        logger.debug("Request: {}", inputStreamToString(input.getContent()));
    } catch (Exception e) {
        logger.error("Error during JSON message creation: ", e);
    }
    return input;
}

From source file:eu.trentorise.smartcampus.network.RemoteConnector.java

public static String putJSON(String host, String service, String body, String token,
        Map<String, Object> parameters) throws SecurityException, RemoteException {
    final HttpResponse resp;

    String queryString = generateQueryString(parameters);
    String uriString = normalizeURL(host + service) + queryString;

    final HttpPut put = new HttpPut(uriString);

    put.setHeader(RH_ACCEPT, "application/json");
    put.setHeader(RH_AUTH_TOKEN, bearer(token));

    try {//from   w  w  w  . ja va2s . com
        if (body != null) {
            StringEntity input = new StringEntity(body, DEFAULT_CHARSET);
            input.setContentType("application/json");
            put.setEntity(input);
        }

        resp = getHttpClient().execute(put);
        String response = EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return response;
        }
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN
                || resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new SecurityException();
        }
        throw new RemoteException("Error validating " + resp.getStatusLine());
    } catch (final Exception e) {
        throw new RemoteException(e.getMessage(), e);
    }
}

From source file:eu.trentorise.smartcampus.network.RemoteConnector.java

public static String postJSON(String host, String service, String body, String token,
        Map<String, Object> parameters) throws SecurityException, RemoteException {

    String queryString = generateQueryString(parameters);
    final HttpResponse resp;
    final HttpPost post = new HttpPost(normalizeURL(host + service) + queryString);

    post.setHeader(RH_ACCEPT, "application/json");
    post.setHeader(RH_AUTH_TOKEN, bearer(token));

    try {//from   www  .j  a v  a 2  s .  c o m
        StringEntity input = new StringEntity(body, DEFAULT_CHARSET);
        input.setContentType("application/json");
        post.setEntity(input);

        resp = getHttpClient().execute(post);
        String response = EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return response;
        }
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN
                || resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new SecurityException();
        }

        String msg = "";
        try {
            msg = response.substring(response.indexOf("<h1>") + 4,
                    response.indexOf("</h1>", response.indexOf("<h1>")));
        } catch (Exception e) {
            msg = resp.getStatusLine().toString();
        }
        throw new RemoteException(msg);
    } catch (ClientProtocolException e) {
        throw new RemoteException(e.getMessage(), e);
    } catch (ParseException e) {
        throw new RemoteException(e.getMessage(), e);
    } catch (IOException e) {
        throw new RemoteException(e.getMessage(), e);
    }
}

From source file:com.bright.json.JSonRequestor.java

public static String doRequest(String jsonReq, String myURL, List<Cookie> cookies) {
    try {/*  www  .j ava2 s  .co m*/

        /* HttpClient httpclient = new DefaultHttpClient(); */

        HttpClient httpclient = getNewHttpClient();
        CookieStore cookieStore = new BasicCookieStore();
        Cookie[] cookiearray = cookies.toArray(new Cookie[0]);
        cookieStore.addCookie(cookiearray[0]);
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        /* httpclient = WebClientDevWrapper.wrapClient(httpclient); */

        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        HttpParams params = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 1000);
        HttpConnectionParams.setSoTimeout(params, 1000);
        HttpPost httppost = new HttpPost(myURL);
        StringEntity stringEntity = new StringEntity(jsonReq);
        stringEntity.setContentType("application/json");
        httppost.setEntity(stringEntity);

        System.out.println("executing request " + httppost.getRequestLine()
                + System.getProperty("line.separator") + jsonReq);

        HttpResponse response = httpclient.execute(httppost, localContext);

        System.out.println(response + "\n");
        for (Cookie c : ((AbstractHttpClient) httpclient).getCookieStore().getCookies()) {
            System.out.println("\n Cookie: " + c.toString() + "\n");
        }

        HttpEntity resEntity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("Response content length: " + resEntity.getContentLength());
            System.out.println("Chunked?: " + resEntity.isChunked());
            String message = new String(EntityUtils.toString(resEntity));
            System.out.println(message);
            return message;
        }
        EntityUtils.consume(resEntity);

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

    return null;

}

From source file:co.aurasphere.botmill.fb.internal.util.network.NetworkUtils.java

/**
 * Utility method that converts an object to its StringEntity
 * representation./*from   w ww. j a va  2 s.  c  o  m*/
 * 
 * @param object
 *            the object to convert to a StringEntity.
 * @return a {@link StringEntity} object containing the object JSON.
 */
private static StringEntity toStringEntity(Object object) {
    StringEntity input = null;
    try {
        String json = JsonUtils.toJson(object);
        input = new StringEntity(json, StandardCharsets.UTF_8);
        input.setContentType("application/json");
        logger.debug("Request: {}", inputStreamToString(input.getContent()));
    } catch (Exception e) {
        logger.error("Error during JSON message creation: ", e);
    }
    return input;
}