List of usage examples for org.apache.http.util EntityUtils toString
public static String toString(HttpEntity httpEntity) throws IOException, ParseException
From source file:com.li.tools.httpclient.util.ClientWithResponseHandler.java
public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*from ww w . j a va 2 s.c o m*/ HttpGet httpget = new HttpGet("http://httpbin.org/"); System.out.println("Executing request " + httpget.getRequestLine()); // Create a custom response handler ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override 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) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = httpclient.execute(httpget, responseHandler); System.out.println("----------------------------------------"); System.out.println(responseBody); } finally { httpclient.close(); } }
From source file:com.wolfsoftco.httpclient.RestClient.java
@SuppressWarnings("resource") public static void main(String[] args) { CloseableHttpClient httpclient = null; CloseableHttpResponse response = null; try {/*from w w w . java2 s.co m*/ HttpEntity entity = null; String responseHtml = null; httpclient = HttpClients.custom().build(); //Based on CURL line: //curl localhost:9090/oauth/token -d "grant_type=password&scope=write&username=greg&password=turnquist" -u foo:bar //clientid:secret String clientID = "foo:bar"; HttpUriRequest login = RequestBuilder.post().setUri(new URI(URL)) .addHeader("Authorization", "Basic " + Base64.encodeBase64String(clientID.getBytes())) .addParameter("grant_type", "password").addParameter("scope", "read") .addParameter("username", "greg").addParameter("password", "turnquist").build(); response = httpclient.execute(login); entity = response.getEntity(); responseHtml = EntityUtils.toString(entity); EntityUtils.consume(entity); JsonObject jsonObject = null; String token = null; if (responseHtml.startsWith("{")) { JsonParser parser = new JsonParser(); jsonObject = parser.parse(responseHtml).getAsJsonObject(); token = jsonObject.get("access_token").getAsString(); } if (token != null) { HttpGet request = new HttpGet(URL_FLIGHTS); request.addHeader("Authorization", "Bearer " + token); response = httpclient.execute(request); entity = response.getEntity(); responseHtml = EntityUtils.toString(entity); EntityUtils.consume(entity); System.out.println(responseHtml); } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (httpclient != null) httpclient.close(); if (response != null) response.close(); } catch (IOException e) { } } }
From source file:com.hsbc.frc.SevenHero.ClientExecuteProxy.java
public static void main(String[] args) throws Exception { HttpHost proxy = new HttpHost("133.13.162.149", 8080, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); try {/*from w ww .ja va 2s. co m*/ httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); HttpHost target = new HttpHost("pt.3g.qq.com"); HttpGet req = new HttpGet("/"); System.out.println("executing request to " + target + " via " + proxy); HttpResponse rsp = httpclient.execute(target, req); 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)); } } 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:com.dlmu.heipacker.crawler.client.ClientExecuteProxy.java
public static void main(String[] args) throws Exception { HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); try {/* ww w .j a v a2s . co m*/ httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); HttpHost target = new HttpHost("issues.apache.org", 443, "https"); HttpGet req = new HttpGet("/"); System.out.println("executing request to " + target + " via " + proxy); HttpResponse rsp = httpclient.execute(target, req); 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)); } } 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:com.http.my.ClientFormLogin.java
public static void main(String[] args) throws Exception { ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); System.out.println(response.getStatusLine()); if (status >= 200 && status < 303) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); }/* w w w . j av a 2s . c o m*/ } }; BasicCookieStore cookieStore = new BasicCookieStore(); // // BasicClientCookie cookieJSESSIONID = new BasicClientCookie("JSESSIONID", "3FD927DC6911B719E4492E7473897FBA"); // cookieJSESSIONID.setVersion(0); // cookieJSESSIONID.setDomain("218.75.79.230"); // cookieJSESSIONID.setPath("/"); // System.out.println("Initial set of cookies:"); // cookieStore.addCookie(cookieJSESSIONID); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); // HttpProtocolParams.setUserAgent(httpclient.getParams(), "Mozilla/5.0 (Windows; U; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)"); try { // HttpPost httpost = new HttpPost("http://localhost:8081/cring/jsp/user/userLogin.do?method=login"); HttpPost loginpost = new HttpPost("http://134.96.41.47/ecommunications_chs/start.swe"); //HttpGet loginGet = new HttpGet("http://134.96.41.47/ecommunications_chs/start.swe"); // HttpGet loginGet = new HttpGet("http://www.baidu.com"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("SWEUserName", "nili")); nvps.add(new BasicNameValuePair("SWEPassword", "nili7788")); nvps.add(new BasicNameValuePair("SWEFo", "SWEEntryForm")); nvps.add(new BasicNameValuePair("SWENeedContext", "false")); nvps.add(new BasicNameValuePair("SWECmd", "ExecuteLogin")); nvps.add(new BasicNameValuePair("W", "t")); nvps.add(new BasicNameValuePair("SWEC", "0")); nvps.add(new BasicNameValuePair("SWEBID", "-1")); nvps.add(new BasicNameValuePair("SWETS", "1385712482625")); /** * SWEUserName:111111 SWEPassword:222222 SWEFo:SWEEntryForm SWENeedContext:false SWECmd:ExecuteLogin W:t SWESPNR: SWESPNH: SWEH: SWEC:0 SWEW: SWEBID:-1 SWETS:1385712482625 SWEWN: */ loginpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // CloseableHttpResponse response = httpclient.execute(loginpost); // HttpEntity httpEntity = response.getEntity(); CloseableHttpResponse responseGet = httpclient.execute(loginpost); HttpEntity httpEntityGet = responseGet.getEntity(); System.out.println("statusLine: " + responseGet.getStatusLine()); System.out.println("ContentType: " + httpEntityGet.getContentType()); System.out.println("ContentLength: " + httpEntityGet.getContentLength()); // httpEntityGet.get System.out.println("loginGet: " + EntityUtils.toString(httpEntityGet)); /* try { System.out.println("Post logon cookies:"); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } HttpPost modifypost = new HttpPost("http://localhost:8081/cring/jsp/user/corpUserController.do?method=modifyPwd"); List <NameValuePair> modifynvps = new ArrayList <NameValuePair>(); modifynvps.add(new BasicNameValuePair("newPwd","111111")); modifypost.setEntity(new UrlEncodedFormEntity(modifynvps, Consts.UTF_8)); CloseableHttpResponse modifyresponse = httpclient.execute(modifypost); System.out.println("modifyresponse : "+modifyresponse.getStatusLine()); } finally { //response2.close(); }*/ } finally { httpclient.close(); } }
From source file:com.http.ClientWithResponseHandler.java
public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {// ww w .j a va 2 s .c om HttpGet httpget = new HttpGet("http://www.google.com/"); System.out.println("executing request " + httpget.getURI()); // 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(); System.out.println(response.getStatusLine()); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); entity = new BufferedHttpEntity(entity); System.out.println("---1-----:" + EntityUtils.toString(entity)); System.out.println("---2-----:" + EntityUtils.toString(entity)); return entity != null ? EntityUtils.toString(entity) : 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("----------------------------------------"); } finally { httpclient.close(); } }
From source file:pt.souplesse.spark.Server.java
public static void main(String[] args) { EntityManagerFactory factory = Persistence.createEntityManagerFactory("guestbook"); EntityManager manager = factory.createEntityManager(); JinqJPAStreamProvider streams = new JinqJPAStreamProvider(factory); get("/messages", (req, rsp) -> { rsp.type("application/json"); return gson.toJson(streams.streamAll(manager, Message.class).collect(Collectors.toList())); });//w w w .j a v a 2 s .c o m post("/messages", (req, rsp) -> { try { Message msg = gson.fromJson(req.body(), Message.class); if (StringUtils.isBlank(msg.getMessage()) || StringUtils.isBlank(msg.getName())) { halt(400); } manager.getTransaction().begin(); manager.persist(msg); manager.getTransaction().commit(); } catch (JsonSyntaxException e) { halt(400); } rsp.type("application/json"); return gson.toJson(streams.streamAll(manager, Message.class).collect(Collectors.toList())); }); get("/comments", (req, rsp) -> { rsp.type("application/json"); Map<String, List<Body>> body = new HashMap<>(); try (CloseableHttpClient client = create().build()) { String url = String.format("https://api.github.com/repos/%s/events", req.queryMap("repo").value()); log.info(url); body = client.execute(new HttpGet(url), r -> { List<Map<String, Object>> list = gson.fromJson(EntityUtils.toString(r.getEntity()), List.class); Map<String, List<Body>> result = new HashMap<>(); list.stream().filter(m -> m.getOrDefault("type", "").equals("IssueCommentEvent")) .map(m -> new Body(((Map<String, String>) m.get("actor")).get("login"), ((Map<String, Map<String, String>>) m.get("payload")).get("comment") .get("body"))) .forEach(b -> result.compute(b.getLogin(), (k, v) -> v == null ? new ArrayList<>() : Lists.asList(b, v.toArray(new Body[v.size()])))); return result; }); } catch (IOException e) { log.error(null, e); halt(400, e.getMessage()); } return gson.toJson(body); }); }
From source file:com.mtea.macrotea_httpclient_study.ClientExecuteProxy.java
public static void main(String[] args) throws Exception { //?//from w w w . ja va2s . co m HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); try { //httpclient??? httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); //? HttpHost target = new HttpHost("issues.apache.org", 443, "https"); HttpGet req = new HttpGet("/"); System.out.println("executing request to " + target + " via " + proxy); HttpResponse rsp = httpclient.execute(target, req); 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)); } } finally { //??httpclient??? httpclient.getConnectionManager().shutdown(); } }
From source file:interoperabilite.webservice.client.ClientEvictExpiredConnections.java
public static void main(String[] args) throws Exception { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(100);/*from w w w . j a v a 2 s. c o m*/ CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).evictExpiredConnections() .evictIdleConnections(5L, TimeUnit.SECONDS).build(); try { // create an array of URIs to perform GETs on String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core-ga/", "http://hc.apache.org/httpcomponents-client-ga/", }; for (int i = 0; i < urisToGet.length; i++) { String requestURI = urisToGet[i]; HttpGet request = new HttpGet(requestURI); System.out.println("Executing request " + requestURI); CloseableHttpResponse response = httpclient.execute(request); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); } finally { response.close(); } } PoolStats stats1 = cm.getTotalStats(); System.out.println("Connections kept alive: " + stats1.getAvailable()); // Sleep 10 sec and let the connection evictor do its job Thread.sleep(10000); PoolStats stats2 = cm.getTotalStats(); System.out.println("Connections kept alive: " + stats2.getAvailable()); } finally { httpclient.close(); } }
From source file:com.alexjalg.gson_google.EjecutarHttpClient.java
public static void main(String[] args) throws Exception { HttpProcessor httpproc = HttpProcessorBuilder.create().add(new RequestContent()) .add(new RequestTargetHost()).add(new RequestConnControl()).add(new RequestUserAgent("Test/1.1")) .add(new RequestExpectContinue(true)).build(); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpCoreContext coreContext = HttpCoreContext.create(); HttpHost host = new HttpHost("jsonplaceholder.typicode.com", 80); coreContext.setTargetHost(host);/* w ww. j av a2s .com*/ DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024); ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE; try { String[] targets = { "/posts" }; for (int i = 0; i < targets.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket); } BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); httpexecutor.preProcess(request, httpproc, coreContext); HttpResponse response = httpexecutor.execute(request, conn, coreContext); httpexecutor.postProcess(response, httpproc, coreContext); System.out.println("<< Response: " + response.getStatusLine()); // System.out.println(EntityUtils.toString(response.getEntity())); String json = EntityUtils.toString(response.getEntity()); ArrayList<Posts> listPosts = new ArrayList<Posts>(); Type listType = new TypeToken<ArrayList<Posts>>() { }.getType(); listPosts = new Gson().fromJson(json, listType); for (Posts post : listPosts) { System.out.println(""); System.out.println(post.getUserId()); System.out.println(post.getId()); System.out.println(post.getTitle()); System.out.println(post.getBody()); } System.out.println("=============="); if (!connStrategy.keepAlive(response, coreContext)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }