Example usage for org.apache.http.util EntityUtils toString

List of usage examples for org.apache.http.util EntityUtils toString

Introduction

In this page you can find the example usage for org.apache.http.util EntityUtils toString.

Prototype

public static String toString(HttpEntity httpEntity, String str) throws IOException, ParseException 

Source Link

Usage

From source file:App.App.java

public static void main(String[] args) throws IOException {
    File inFile = new File("C:\\Data\\LogTest.java");
    FileInputStream fis = new FileInputStream(inFile);
    DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
    HttpPost httppost = new HttpPost("http://localhost:8080/rest_j2ee/rest/files/upload");
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("file", new InputStreamBody(fis, inFile.getName()));
    httppost.setEntity(entity);/*from ww  w  .  j ava  2 s  . com*/
    HttpResponse response = httpclient.execute(httppost);
    int statusCode = response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = response.getEntity();
    String responseString = EntityUtils.toString(responseEntity, "UTF-8");
    System.out.println("[" + statusCode + "] " + responseString);
}

From source file:com.sim.demo.httpclient.httpget.BaiduDemo.java

/**
 * @param args/* ww  w . j  a  v a  2  s. c  o  m*/
 * @throws IOException 
 * @throws ClientProtocolException 
 */
public static void main(String[] args) throws ClientProtocolException, IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpGet httpGet = new HttpGet("http://www.baidu.com");

    System.out.println(httpGet.getURI().toString());

    CloseableHttpResponse response = httpClient.execute(httpGet);

    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == 200) {
        HttpEntity entity = response.getEntity();

        String context = EntityUtils.toString(entity, "UTF-8");

        System.out.println("context : " + context);
    }

    httpClient.close();

}

From source file:com.sim.demo.httpclient.httpget.SinaDemo.java

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

    CloseableHttpClient httpClient = HttpClients.createDefault();
    // HttpGet/*from  w ww  .ja  v a 2  s .c o m*/
    HttpGet httpGet = new HttpGet("http://www.sina.com");
    System.out.println("executing request " + httpGet.getURI());
    // get
    HttpResponse response = httpClient.execute(httpGet);
    // ??
    HttpEntity entity = response.getEntity();
    // ???
    System.out.println(response.getStatusLine());
    if (entity != null) {
        // ??
        System.out.println("Response content lenght:" + entity.getContentLength());
        String content = EntityUtils.toString(entity, "UTF-8").trim();
        // HttpClient?? String?
        System.out.println("Response content:" + content);
    }
    // ?
    httpClient.close();
}

From source file:sadl.run.moe.MoeTest2.java

public static void main(String[] args) throws ClientProtocolException, IOException {
    final String postUrl = "http://pc-kbpool-8.cs.upb.de:6543/gp/next_points/epi";// put in your url
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { // Use this instead
        final HistoryData h = new HistoryData();
        final Configuration c = new Configuration();
        final PdttaParameters parameters = new PdttaParameters();
        for (final Parameter p : parameters.parameters) {
            c.config.put(p, p.getDefault());
        }/* w ww.  j av  a  2s. c o  m*/
        h.history.put(c, 0.5);
        final HttpPost post = new HttpPost(postUrl);
        final String s = parameters.toJsonString(20, h);
        // final String s = Files.readAllLines(Paths.get("testfile")).get(0);
        // final StringEntity postingString = new StringEntity(gson.toJson(p));// convert your pojo to json
        final StringEntity postingString = new StringEntity(s);// convert your pojo to json
        post.setEntity(postingString);
        System.out.println(EntityUtils.toString(post.getEntity(), "UTF-8"));
        post.setHeader("Content-type", "application/json");
        try (CloseableHttpResponse response = httpClient.execute(post)) {
            final String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(responseString);
        }
    }
    // This is the right query
    // {"domain_info": {"dim": 2, "domain_bounds": [{"max": 1.0, "min": 0.0},{"max": 0.0, "min": -1.0}]}, "gp_historical_info": {"points_sampled":
    // [{"value_var": 0.01, "value": 0.1, "point": [0.0,0.0]}, {"value_var": 0.01, "value": 0.2, "point": [1.0,-1.0]}]}, "num_to_sample": 1}
}

From source file:com.kolich.http.BlockingTest.java

public static void main(String[] args) {

    final HttpClient client = getNewInstanceWithProxySelector("foobar");

    final Either<Integer, String> result = new HttpClient4Closure<Integer, String>(client) {
        @Override//from   w w w . ja va  2s . c  o  m
        public void before(final HttpRequestBase request) {
            request.addHeader("Authorization", "super-secret-password");
        }

        @Override
        public String success(final HttpSuccess success) throws Exception {
            return EntityUtils.toString(success.getResponse().getEntity(), UTF_8);
        }

        @Override
        public Integer failure(final HttpFailure failure) {
            return failure.getStatusCode();
        }
    }.get("http://google.com");
    if (result.success()) {
        System.out.println(result.right());
    } else {
        System.out.println(result.left());
    }

    final Either<Void, Header[]> hResult = new HttpClient4Closure<Void, Header[]>(client) {
        @Override
        public Header[] success(final HttpSuccess success) throws Exception {
            return success.getResponse().getAllHeaders();
        }
    }.head("http://example.com");
    if (hResult.success()) {
        System.out.println("Fetched " + hResult.right().length + " request headers.");
    }

    final Either<Void, String> sResult = new StringOrNullClosure(client).get("http://mark.koli.ch");
    if (sResult.success()) {
        System.out.println(sResult.right());
    } else {
        System.out.println(sResult.left());
    }

    final Either<Exception, String> eResult = new HttpClient4Closure<Exception, String>(client) {
        @Override
        public String success(final HttpSuccess success) throws Exception {
            return EntityUtils.toString(success.getResponse().getEntity(), UTF_8);
        }

        @Override
        public Exception failure(final HttpFailure failure) {
            return failure.getCause();
        }
    }.put("http://lskdjflksdfjslkf.jfjkfhddfgsdfsdf.com");
    if (!eResult.success()) {
        System.out.println(eResult.left());
    }

    // Custom check for "success".
    final Either<Exception, String> cResult = new HttpClient4Closure<Exception, String>(client) {
        @Override
        public boolean check(final HttpResponse response, final HttpContext context) {
            return (response.getStatusLine().getStatusCode() == 405);
        }

        @Override
        public String success(final HttpSuccess success) throws Exception {
            return EntityUtils.toString(success.getResponse().getEntity(), UTF_8);
        }
    }.put("http://google.com");
    if (cResult.success()) {
        System.out.println(cResult.right());
    }

    final Either<Exception, OutputStream> bResult = new HttpClient4Closure<Exception, OutputStream>(client) {
        @Override
        public OutputStream success(final HttpSuccess success) throws Exception {
            final OutputStream os = new ByteArrayOutputStream();
            IOUtils.copy(success.getResponse().getEntity().getContent(), os);
            return os;
        }

        @Override
        public Exception failure(final HttpFailure failure) {
            return failure.getCause();
        }
    }.get("http://google.com");
    if (bResult.success()) {
        System.out.println("Loaded bytes into output stream!");
    }

    final OutputStream os = new ByteArrayOutputStream();
    final Either<Exception, Integer> stResult = new HttpClient4Closure<Exception, Integer>(client) {
        @Override
        public Integer success(final HttpSuccess success) throws Exception {
            return IOUtils.copy(success.getResponse().getEntity().getContent(), os);
        }
        /*
        @Override
        public Exception failure(final HttpFailure failure) {
           return failure.getCause();
        }
        */
    }.get("http://mark.koli.ch");
    if (stResult.success()) {
        System.out.println("Loaded " + stResult.right() + " bytes.");
    }

    /*
    final HttpContext context = new BasicHttpContext();
    // Setup a basic cookie store so that the response can fetch
    // any cookies returned by the server in the response.
    context.setAttribute(COOKIE_STORE, new BasicCookieStore());
    final Either<Void,String> cookieResult =
       new HttpClientClosureExpectString(client)
    .get(new HttpGet("http://google.com"), context);
    if(cookieResult.success()) {
       // List out all cookies that came back from Google in the response.
       final CookieStore cookies = (CookieStore)context.getAttribute(COOKIE_STORE);
       for(final Cookie c : cookies.getCookies()) {
    System.out.println(c.getName() + " -> " + c.getValue());
       }
    }*/

    final Either<Integer, List<Cookie>> mmmmm = new HttpClient4Closure<Integer, List<Cookie>>(client) {
        @Override
        public void before(final HttpRequestBase request, final HttpContext context) {
            context.setAttribute(COOKIE_STORE, new BasicCookieStore());
        }

        @Override
        public List<Cookie> success(final HttpSuccess success) {
            // Extract a list of cookies from the request.
            // Might be empty.
            return ((CookieStore) success.getContext().getAttribute(COOKIE_STORE)).getCookies();
        }

        @Override
        public Integer failure(final HttpFailure failure) {
            return failure.getStatusCode();
        }
    }.get("http://google.com");
    final List<Cookie> cookies;
    if ((cookies = mmmmm.right()) != null) {
        for (final Cookie c : cookies) {
            System.out.println(c.getName() + " -> " + c.getValue());
        }
    } else {
        System.out.println("Failed miserably: " + mmmmm.left());
    }

    final Either<Void, Header[]> haResult = new HttpClient4Closure<Void, Header[]>(client) {
        @Override
        public Header[] success(final HttpSuccess success) {
            return success.getResponse().getAllHeaders();
        }
    }.head("http://java.com");
    final Header[] headers = haResult.right();
    if (headers != null) {
        for (final Header h : headers) {
            System.out.println(h.getName() + ": " + h.getValue());
        }
    }

}

From source file:test.ClientTest.java

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpHost proxy = new HttpHost("192.168.1.158", 8080, "http");
    //      httpclient.getCredentialsProvider().setCredentials(new AuthScope("192.168.1.158", 8080),new UsernamePasswordCredentials("", ""));
    try {/*from  ww w .  j a v  a 2  s  . c  o  m*/
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        HttpHost target = new HttpHost("www.drugoogle.com", 80, "http");
        HttpGet httpget = new HttpGet("/index/index.htm");

        System.out.println("executing request to " + httpget);

        HttpResponse rsp = httpclient.execute(target, httpget);
        HttpEntity entity = rsp.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(rsp.getStatusLine());
        Header[] headers = rsp.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            System.out.println(headers[i]);
        }
        System.out.println("----------------------------------------");

        if (entity != null) {
            System.out.println(EntityUtils.toString(entity, "UTF-8"));
        }

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

From source file:test.AsyncClientCustomContext.java

public final static void main(String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    HttpEntity entity = null;/*from  w  w  w.  j av a 2  s  .co  m*/
    String jsonContent = "";
    try {
        // Create a local instance of cookie store
        CookieStore cookieStore = new BasicCookieStore();

        // Create local HTTP context
        HttpClientContext localContext = HttpClientContext.create();
        // Bind custom cookie store to the local context
        localContext.setCookieStore(cookieStore);

        HttpGet httpget = new HttpGet("http://viphp.sinaapp.com/baidu/translate/translate.php?origin=");
        System.out.println("Executing request " + httpget.getRequestLine());

        httpclient.start();

        // Pass local context as a parameter
        Future<HttpResponse> future = httpclient.execute(httpget, localContext, null);

        // Please note that it may be unsafe to access HttpContext instance
        // while the request is still being executed
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        entity = response.getEntity();
        jsonContent = EntityUtils.toString(entity, "UTF-8");
        System.out.println("jsonContent:" + jsonContent);
        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("Local cookie: " + cookies.get(i));
        }
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
}

From source file:testing01.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String outputFile = "test.html";
    String baseWebSite = "http://www.ettoday.net/news/20130802/250478.htm";
    try {//from  w w w .  j av a 2  s  . c o  m
        //HttpGet httpGet = new HttpGet(baseWebSite + "cat/politic/r");
        HttpGet httpGet = new HttpGet(baseWebSite);
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response
        // object
        // to allow the response content to be streamed directly from the
        // network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally
        // clause.
        // Please note that if response content is not fully consumed the
        // underlying
        // connection cannot be safely re-used and will be shut down and
        // discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            String responseString = EntityUtils.toString(entity1, "UTF-8");
            // System.out.println(responseString);
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF8"));
            out.write(responseString);
            out.close();
            EntityUtils.consume(entity1);
            System.out.println(baseWebSite + " output to " + outputFile + " successful");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            response1.close();
        }
        /*
         * HttpPost httpPost = new HttpPost("http://targethost/login"); List
         * <NameValuePair> nvps = new ArrayList <NameValuePair>();
         * nvps.add(new BasicNameValuePair("username", "vip")); nvps.add(new
         * BasicNameValuePair("password", "secret")); httpPost.setEntity(new
         * UrlEncodedFormEntity(nvps)); CloseableHttpResponse response2 =
         * httpclient.execute(httpPost);
         * 
         * try { System.out.println(response2.getStatusLine()); HttpEntity
         * entity2 = response2.getEntity(); // do something useful with the
         * response body // and ensure it is fully consumed
         * EntityUtils.consume(entity2); } finally { response2.close(); }
         */
    } finally {
        httpclient.close();
    }
}

From source file:com.luqili.http.ssl.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    String sslKeyStorePath = "/mnt/data2/clientkey/370900.pfx";
    String sslKeyStorePassword = "370900";
    String sslKeyStoreType = "PKCS12"; // JKS PKCS12
    String sslTrustStore = "/mnt/data2/clientkey/PengeSoftOARoot.cer";
    String sslTrustStorePassword = "";
    String url = "https://123.57.205.217:8082/Service/UpReportInfoServiceSvr.assx/UpReportInfo";
    String content = "Token=&CityCodes=370900&CountyCodes=&DealDate=2016-06-16T00:00:00&Reportor=?&NewBusinessArea=1000.88&NewBusinessAmount=9898&NewHouseArea=5000&NewHouseAmount=8000&NewHouseCount=20&OldReportor=?&OldBusinessArea=1234.56&OldBusinessAmount=80000&OldHouseArea=12580&OldHouseAmount=99999&OldHouseCount=100";
    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom()
            .loadTrustMaterial(new File(sslKeyStorePath), sslKeyStorePassword.toCharArray(),
                    new TrustSelfSignedStrategy())
            .loadKeyMaterial(new File(sslKeyStorePath), sslKeyStorePassword.toCharArray(),
                    sslKeyStorePassword.toCharArray())
            .build();//from  w  w  w .  ja  v  a2  s.  c o  m
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpPost httppost = new HttpPost(url);

        System.out.println("Executing request " + httppost.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, "UTF-8").trim();
                if (!"True".toUpperCase().equals(result.toUpperCase())) {
                    System.out.println(result);
                }
            }

            System.out.println(response.getStatusLine());
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:org.apache.http.examples.client.ClientWithResponseHandlerForUms.java

public final static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    //    DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
    //    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    try {/*from   w ww . j  a  va2 s .  com*/
        //      String url = "http://mxyinghang.com/pay/ums/umsLogin.htm";
        String url = "http://cs.com:8080/web/ums/verify";
        HttpGet httpget = new HttpGet(url);
        httpget.setHeader("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        httpget.setHeader("Accept-Encoding", "gzip, deflate, sdch");
        httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
        httpget.setHeader("Cache-Control", "no-cache");
        httpget.setHeader("Connection", "keep-alive");
        httpget.setHeader("Referer", "http://mxyinghang.com/richboss/");
        httpget.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36");

        System.out.println("Executing request httpget.getRequestLine() " + httpget.getRequestLine());

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity, "utf-8") : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);

        System.out.println("----------------------------------------");
        //      ObjectMapper mapper = new ObjectMapper();
        //      mapper.readValue(responseBody, AddressCoord.class);
        //      JsonNode root = mapper.readTree(responseBody.substring("showLocation&&showLocation(".length(), responseBody.length()-1));

    } finally {
        httpclient.close();
    }
}