List of usage examples for org.apache.http.impl.client CloseableHttpClient execute
public <T> T execute(final HttpUriRequest request, final ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException
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 w w. j av a2 s .co m*/ // 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(); } }
From source file:org.apache.http.examples.client.ClientWithResponseHandler.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 ww w. j a v a 2s . co m // HttpGet httpget = new HttpGet("http://localhost/"); HttpGet httpget = new HttpGet( "http://api.map.baidu.com/geocoder/v2/?address=&output=json&ak=E4805d16520de693a3fe707cdc962045&callback=showLocation"); // httpget.setHeader("Accept", "180.97.33.90:80"); 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://developer.baidu.com/map/index.php?title=webapi/guide/changeposition"); 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); //showLocation&&showLocation({"status":0,"result":{"location":{"lng":112.25009284837,"lat":32.229168591538},"precise":0,"confidence":14,"level":"\u533a\u53bf"}}) System.out.println("----------------------------------------"); ObjectMapper mapper = new ObjectMapper(); // mapper.readValue(responseBody, AddressCoord.class); JsonNode root = mapper.readTree( responseBody.substring("showLocation&&showLocation(".length(), responseBody.length() - 1)); // String name = root.get("name").asText(); // int age = root.get("age").asInt(); String status = root.get("status").asText(); String lng = root.with("result").with("location").get("lng").asText(); String lat = root.with("result").with("location").get("lat").asText(); String level = root.with("result").get("level").asText(); System.out.println(String.format("'%1$s': [%2$s, %3$s], status: %4$s", level, lng, lat, status)); } finally { httpclient.close(); } }
From source file:tv.icntv.common.HttpClientUtil.java
/** * Get content by url as string/*w w w . j a v a2 s . c om*/ * * @param url original url * @return page content * @throws java.io.IOException */ public static String getContent(String url) throws IOException { // construct request HttpGet request = new HttpGet(url); request.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")); request.setConfig(RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT) .setSocketTimeout(SOCKET_TIMEOUT).build()); // construct response handler ResponseHandler<String> handler = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse response) throws IOException { StatusLine status = response.getStatusLine(); // status if (status.getStatusCode() != HttpStatus.SC_OK) { throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()); } // get encoding in header String encoding = getPageEncoding(response); boolean encodingFounded = true; if (Strings.isNullOrEmpty(encoding)) { encodingFounded = false; encoding = "iso-8859-1"; } // get content and find real encoding HttpEntity entity = response.getEntity(); if (entity == null) { return null; } // get content byte[] contentBytes = EntityUtils.toByteArray(entity); if (contentBytes == null) { return null; } // found encoding if (encodingFounded) { return new String(contentBytes, encoding); } // attempt to discover encoding String rawContent = new String(contentBytes, DEFAULT_ENCODING); Matcher matcher = PATTERN_HTML_CHARSET.matcher(rawContent); if (matcher.find()) { String realEncoding = matcher.group(1); if (!encoding.equalsIgnoreCase(realEncoding)) { // bad luck :( return new String(rawContent.getBytes(encoding), realEncoding); } } // not found right encoding :) return rawContent; } }; // execute CloseableHttpClient client = HttpClientHolder.getClient(); return client.execute(request, handler); }
From source file:org.jboss.pnc.mavenrepositorymanager.ArtifactUploadUtils.java
public static boolean put(CloseableHttpClient client, String url, String content) throws IOException { HttpPut put = new HttpPut(url); put.setEntity(new StringEntity(content)); return client.execute(put, response -> { try {/*from ww w.j a v a 2 s . c om*/ return response.getStatusLine().getStatusCode() == 201; } finally { if (response instanceof CloseableHttpResponse) { IOUtils.closeQuietly((CloseableHttpResponse) response); } } }); }
From source file:com.johnson.grab.browser.HttpClientUtil.java
/** * Get content by url as string/* ww w .j ava 2 s . co m*/ * @param url * original url * @return * page content * @throws java.io.IOException */ public static String getContent(String url) throws CrawlException, IOException { // construct request HttpGet request = new HttpGet(url); request.setConfig(RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT) .setSocketTimeout(SOCKECT_TIMEOUT).build()); // construct response handler ResponseHandler<String> handler = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse response) throws IOException { StatusLine status = response.getStatusLine(); // status if (status.getStatusCode() != HttpStatus.SC_OK) { throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()); } // get encoding in header String encoding = getPageEncoding(response); boolean encodingFounded = true; if (StringUtil.isEmpty(encoding)) { encodingFounded = false; encoding = UniversalConstants.Encoding.ISO_8859_1; } // get content and find real encoding HttpEntity entity = response.getEntity(); if (entity == null) { return null; } // get content byte[] contentBytes = EntityUtils.toByteArray(entity); if (contentBytes == null) { return null; } // found encoding if (encodingFounded) { return new String(contentBytes, encoding); } // attempt to discover encoding String rawContent = new String(contentBytes, UniversalConstants.Encoding.DEFAULT); Matcher matcher = PATTERN_HTML_CHARSET.matcher(rawContent); if (matcher.find()) { String realEncoding = matcher.group(1); if (!encoding.equalsIgnoreCase(realEncoding)) { // bad luck :( return new String(rawContent.getBytes(encoding), realEncoding); } } // not found right encoding :) return rawContent; } }; // execute CloseableHttpClient client = HttpClientHolder.getClient(); return client.execute(request, handler); }
From source file:org.xwiki.contrib.repository.pypi.internal.utils.PyPiHttpUtils.java
public static InputStream performGet(URI uri, HttpClientFactory httpClientFactory, HttpContext localContext) throws HttpException { HttpGet getMethod = new HttpGet(uri); CloseableHttpClient httpClient = httpClientFactory.createClient(null, null); CloseableHttpResponse response;//from w w w. j a v a 2s .c o m try { if (localContext != null) { response = httpClient.execute(getMethod, localContext); } else { response = httpClient.execute(getMethod); } } catch (Exception e) { throw new HttpException(String.format("Failed to request [%s]", getMethod.getURI()), e); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { try { return response.getEntity().getContent(); } catch (IOException e) { throw new HttpException( String.format("Failed to parse response body of request [%s]", getMethod.getURI()), e); } } else if (statusCode == HttpStatus.SC_NOT_FOUND) { return null; } else { throw new HttpException(String.format("Invalid answer [%s] from the server when requesting [%s]", response.getStatusLine().getStatusCode(), getMethod.getURI())); } }
From source file:org.lokra.seaweedfs.util.ConnectionUtil.java
/** * Check uri link is alive, the basis for judging response status code. * * @param client httpClient/*from ww w . ja v a 2s . c om*/ * @param url check url * @return When the response status code is 200, the result is true. */ public static boolean checkUriAlive(CloseableHttpClient client, String url) { boolean result = false; CloseableHttpResponse response = null; HttpGet request = new HttpGet(url); try { response = client.execute(request, HttpClientContext.create()); result = response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; } catch (IOException e) { return false; } finally { if (response != null) { try { response.close(); } catch (IOException ignored) { } } request.releaseConnection(); } return result; }
From source file:org.xwiki.contrib.repository.npm.internal.utils.NpmHttpUtils.java
public static InputStream performGet(URI uri, HttpClientFactory httpClientFactory, HttpContext localContext, Header[] headers) throws HttpException { HttpGet getMethod = new HttpGet(uri); getMethod.setHeaders(headers);/*from ww w . j a v a 2 s . c o m*/ CloseableHttpClient httpClient = httpClientFactory.createClient(null, null); CloseableHttpResponse response; try { if (localContext != null) { response = httpClient.execute(getMethod, localContext); } else { response = httpClient.execute(getMethod); } } catch (Exception e) { throw new HttpException(String.format("Failed to request [%s]", getMethod.getURI()), e); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { try { return response.getEntity().getContent(); } catch (IOException e) { throw new HttpException( String.format("Failed to parse response body of request [%s]", getMethod.getURI()), e); } } else { throw new HttpException(String.format("Invalid answer [%s] from the server when requesting [%s]", response.getStatusLine().getStatusCode(), getMethod.getURI())); } }
From source file:me.ixfan.wechatkit.util.HttpClientUtil.java
/** * POST data using the Content-Type <code>multipart/form-data</code>. * This enables uploading of binary files etc. * * @param url URL of request.//from ww w .jav a 2s . c o m * @param textInputs Name-Value pairs of text inputs. * @param binaryInputs Name-Value pairs of binary files inputs. * @return JSON object of response. * @throws IOException If I/O error occurs. */ public static JsonObject sendMultipartRequestAndGetJsonResponse(String url, Map<String, String> textInputs, Map<String, MultipartInput> binaryInputs) throws IOException { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); if (null != textInputs) { textInputs.forEach((k, v) -> multipartEntityBuilder.addTextBody(k, v)); } if (null != binaryInputs) { binaryInputs.forEach((k, v) -> { if (null == v.getDataBytes()) { multipartEntityBuilder.addBinaryBody(k, v.getFile(), v.getContentType(), v.getFile().getName()); } else { multipartEntityBuilder.addBinaryBody(k, v.getDataBytes(), v.getContentType(), v.getFilename()); } }); } CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(url); post.setEntity(multipartEntityBuilder.build()); return httpClient.execute(post, new JsonResponseHandler()); }
From source file:org.keycloak.testsuite.saml.ConcurrentAuthnRequestTest.java
public static void performLogin(HttpUriRequest post, URI samlEndpoint, String relayState, Document samlRequest, CloseableHttpResponse response, final CloseableHttpClient client, UserRepresentation user, RedirectStrategyWithSwitchableFollowRedirect strategy) { try {/*from w w w . ja v a 2 s .c om*/ HttpClientContext context = HttpClientContext.create(); response = client.execute(post, context); String loginPageText = EntityUtils.toString(response.getEntity(), "UTF-8"); response.close(); HttpUriRequest loginRequest = LoginBuilder.handleLoginPage(user, loginPageText); strategy.setRedirectable(false); response = client.execute(loginRequest, context); response.close(); } catch (Exception ex) { throw new RuntimeException(ex); } finally { if (response != null) { EntityUtils.consumeQuietly(response.getEntity()); try { response.close(); } catch (IOException ex) { } } } }