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.sme.SmePoliceCheck.java

public static void main(String[] args) throws IOException, JSONException {

    // This API is for SME
    // After creating Police Check you should Upload documents and then submit the police check
    // 1-Create Police Check
    // 2-Upload Documents for Police Check ID
    // 3-Submit Police Check to Intercheck

    final String apiEndPoint = "https://secure.policecheckexpress.com.au/pce/api/portalCheckSme/new";
    final String apiToken = "secure token";
    try {//  w w  w. j ava  2 s  .co m

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(apiEndPoint);

        //filling Portal Check with sample Data

        SmePortalCheck smePortalCheck = fillSampleData();
        String parameters = fillParameters(smePortalCheck, apiToken);
        StringEntity input = new StringEntity(parameters);
        input.setContentType("application/json");
        postRequest.setEntity(input);
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String jsonText = readAll(br);
        JSONArray json = new JSONArray("[" + jsonText + "]");
        JSONObject obj = (JSONObject) json.get(0);
        if (!(Boolean) obj.get("error")) {

            System.out.println(obj.get("message"));
            System.out.println("Invitation Id = " + obj.get("id"));
        } else {
            System.out.println("++++++++++++++++++++++++++");
            System.out.println("Error  = " + obj.get("message"));
            System.out.println("++++++++++++++++++++++++++");
        }

        httpClient.getConnectionManager().shutdown();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

From source file:com.direct.PortalCheckDirect.java

public static void main(String[] args) throws IOException, JSONException {

    //This API is for Direct Business
    final String apiEndPoint = "https://secure.policecheckexpress.com.au/pce/api/portalCheckDirect/new";
    final String apiToken = "secure Token";
    try {//from w  ww  . j ava2 s .c  o  m

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(apiEndPoint);

        //filling Portal Check with Sample Data
        DirectPortalCheck directPortalCheck = fillSampleData();
        String parameters = fillParameters(directPortalCheck, apiToken);
        StringEntity input = new StringEntity(parameters);
        input.setContentType("application/json");
        postRequest.setEntity(input);
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String jsonText = readAll(br);
        JSONArray json = new JSONArray("[" + jsonText + "]");
        JSONObject obj = (JSONObject) json.get(0);
        if (!(Boolean) obj.get("error")) {

            System.out.println(obj.get("message"));
            System.out.println("Invitation Id = " + obj.get("id"));
        } else {
            System.out.println("++++++++++++++++++++++++++");
            System.out.println("Error  = " + obj.get("message"));
            System.out.println("++++++++++++++++++++++++++");

        }

        httpClient.getConnectionManager().shutdown();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

From source file:com.cloudhopper.httpclient.util.HttpPostMain.java

static public void main(String[] args) throws Exception {
    ////from  w w w.  j a  v a2s .  c  o m
    // target urls
    //
    String strURL = "http://209.226.31.233:9009/SendSmsService/b98183b99a1f473839ce569c78b84dbd";

    // Username: Twitter
    // Password: Twitter123

    TrustManager easyTrustManager = new X509TrustManager() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);

    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", sf, 443);

    //SchemeRegistry sr = new SchemeRegistry();
    //sr.register(http);
    //sr.register(https);

    // create and initialize scheme registry
    //SchemeRegistry schemeRegistry = new SchemeRegistry();
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    //ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    //cm.setMaxTotalConnections(1);

    DefaultHttpClient client = new DefaultHttpClient();

    client.getConnectionManager().getSchemeRegistry().register(https);

    //        for (int i = 0; i < 1; i++) {
    //
    // create a new ticket id
    //
    //String ticketId = TicketUtil.generate(1, System.currentTimeMillis());

    /**
    StringBuilder string0 = new StringBuilder(200)
        .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
        .append("<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n")
        .append("       <S:Header>\n")
        .append("               <ns3:TransactionID xmlns:ns4=\"http://vmp.vzw.com/schema\"\n")
        .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\">" + ticketId + "</ns3:TransactionID>\n")
        .append("       </S:Header>\n")
        .append("       <S:Body>\n")
        .append("               <ns2:OptinReq xmlns:ns4=\"http://schemas.xmlsoap.org/soap/envelope/\"\n")
        .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\"\n")
        .append("xmlns:ns2=\"http://vmp.vzw.com/schema\">\n")
        .append("                      <ns2:VASPID>twitter</ns2:VASPID>\n")
        .append("                      <ns2:VASID>tm33t!</ns2:VASID>\n")
        .append("                      <ns2:ShortCode>800080008001</ns2:ShortCode>\n")
        .append("                      <ns2:Number>9257089093</ns2:Number>\n")
        .append("                      <ns2:Source>provider</ns2:Source>\n")
        .append("                      <ns2:Message/>\n")
        .append("               </ns2:OptinReq>\n")
        .append("       </S:Body>\n")
        .append("</S:Envelope>");
     */

    // simple send sms
    StringBuilder string1 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
            .append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:loc=\"http://www.csapi.org/schema/parlayx/sms/send/v2_3/local\">\n")
            .append("   <soapenv:Header/>\n").append("   <soapenv:Body>\n").append("      <loc:sendSms>\n")
            .append("         <loc:addresses>tel:+16472260233</loc:addresses>\n")
            .append("         <loc:senderName>6388</loc:senderName>\n")
            .append("         <loc:message>Test Message &</loc:message>\n").append("      </loc:sendSms>\n")
            .append("   </soapenv:Body>\n").append("</soapenv:Envelope>\n");

    // startSmsNotification - place to deliver SMS to

    String req = string1.toString();
    logger.debug("Request XML -> \n" + req);

    HttpPost post = new HttpPost(strURL);

    StringEntity postEntity = new StringEntity(req, "ISO-8859-1");
    postEntity.setContentType("text/xml; charset=\"ISO-8859-1\"");
    post.addHeader("SOAPAction", "\"\"");
    post.setEntity(postEntity);

    long start = System.currentTimeMillis();

    client.getCredentialsProvider().setCredentials(new AuthScope("209.226.31.233", AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("Twitter", "Twitter123"));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local 
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpResponse httpResponse = client.execute(post, localcontext);
    HttpEntity responseEntity = httpResponse.getEntity();

    //
    // was the request OK?
    //
    if (httpResponse.getStatusLine().getStatusCode() != 200) {
        logger.error("Request failed with StatusCode=" + httpResponse.getStatusLine().getStatusCode());
    }

    // get an input stream
    String responseBody = EntityUtils.toString(responseEntity);

    long stop = System.currentTimeMillis();

    logger.debug("----------------------------------------");
    logger.debug("Response took " + (stop - start) + " ms");
    logger.debug(responseBody);
    logger.debug("----------------------------------------");
    //        }

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    client.getConnectionManager().shutdown();
}

From source file:com.firewallid.util.FIConnection.java

public static void sendJson(String host, String json) throws UnsupportedEncodingException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(host);

    StringEntity input = new StringEntity(json);
    input.setContentType("application/json");
    postRequest.setEntity(input);//w ww. jav a 2 s.c o m

    HttpResponse response = httpClient.execute(postRequest);
}

From source file:io.kamax.mxisd.util.RestClientUtils.java

public static HttpPost post(String url, String body) {
    StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8);
    entity.setContentType(ContentType.APPLICATION_JSON.toString());
    HttpPost req = new HttpPost(url);
    req.setEntity(entity);/*from   w w w.ja  v a 2  s  .  c  om*/
    return req;
}

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

private static Cliente addCliente(String url, Cliente cliente) throws IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("accept", "application/json; charset=UTF-8");
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    String jsonString = gson.toJson(cliente);
    StringEntity input = new StringEntity(jsonString, "UTF-8");
    input.setContentType("application/json");
    httpPost.setEntity(input);/* w  w  w .  j av a  2s.  com*/
    HttpResponse response = httpClient.execute(httpPost);

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

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

From source file:org.alfresco.utils.HttpUtil.java

/**
 * Populate HTTP message call with given content.
 * /*from   ww w .  j a  v  a2s  .c o m*/
 * @param json {@link JSONObject} content
 * @return {@link StringEntity} content.
 * @throws UnsupportedEncodingException if unsupported
 */
public static StringEntity setMessageBody(final JSONObject json) throws UnsupportedEncodingException {
    if (json == null || json.toString().isEmpty()) {
        throw new IllegalArgumentException("JSON Content is required.");
    }

    StringEntity se = setMessageBody(json.toString());
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, MIME_TYPE_JSON));
    if (logger.isDebugEnabled()) {
        logger.debug("Json string value: " + se);
    }
    return se;
}

From source file:com.mycompany.trader.HTTPTransport.java

public static HttpPost createPost(String resource, String data) {
    try {/* ww  w.ja  v a 2  s .  co m*/
        HttpPost post = new HttpPost(url + resource);
        StringEntity input = new StringEntity(data);
        input.setContentType("application/json");
        post.setEntity(input);
        return post;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:apidemo.APIDemo.java

public static String sendPostJson(String postUrl, String jsonContent, int timeout /*milisecond*/)
        throws Exception {
    RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(timeout)
            .setConnectTimeout(timeout).build();
    try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
            .build()) {/*from  www.  ja  v  a2  s . co  m*/
        HttpPost httpPost = new HttpPost(postUrl);
        StringEntity input = new StringEntity(jsonContent, "UTF-8");
        input.setContentType("application/json");
        httpPost.setEntity(input);
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new IOException("Failed : HTTP getStatusCode: " + response.getStatusLine().getStatusCode()
                        + " HTTP getReasonPhrase: " + response.getStatusLine().getReasonPhrase());
            }
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader((response.getEntity().getContent())))) {
                String output;
                StringBuilder strBuilder = new StringBuilder();
                while ((output = br.readLine()) != null) {
                    strBuilder.append(output);
                }
                return strBuilder.toString();
            }
        }
    }
}

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

private static void loadMenuFile(File file) {
    Scanner scan = null;/*from   ww w .j a v  a  2 s. co m*/
    try {
        scan = new Scanner(file, Loader.encoding);
        // the content is only the data portion. convert to map
        String content = scan.useDelimiter("\\Z").next();
        HttpPost httpPost = new HttpPost("http://injector:8080/api/rs");
        StringEntity input = new StringEntity(content);
        input.setContentType("application/json");
        httpPost.setEntity(input);
        CloseableHttpResponse response = httpclient.execute(httpPost);

        try {
            System.out.println(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();
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (scan != null)
            scan.close();
    }
}