List of usage examples for org.apache.http.impl.client HttpClients createDefault
public static CloseableHttpClient createDefault()
From source file:com.kingmed.dp.ndp.impl.SignInResponseHandlerTest.java
@Test public void testSignIn() { for (NDPServe ndpServe : allNDPServes) { String signinUrl = ndpServe.getUrlSignin(); CloseableHttpClient httpclient = HttpClients.createDefault(); NDPServeResponseHandler responeHandler = new SignInResponseHandler(); try {/* w w w . java 2 s . c om*/ HttpGet httpget = new HttpGet(signinUrl); String cookie = httpclient.execute(httpget, responeHandler); Assert.notNull(cookie); } catch (Exception e) { e.printStackTrace(); fail("?"); } } }
From source file:driimerfinance.helpers.FinanceHelper.java
/** * Checks if the license is valid using the License Key Server * * @param license key to check//from w ww . ja v a 2s. c om * @return validity of the license (true or false) */ public static boolean checkLicense(String licenseKey) { HttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost("http://driimerfinance.michaelkohler.info/checkLicense"); List<NameValuePair> params = new ArrayList<NameValuePair>(2); params.add(new BasicNameValuePair("key", licenseKey)); // pass the key to the server try { httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); } catch (UnsupportedEncodingException e) { return false; } HttpResponse response = null; try { response = httpclient.execute(httppost); // get the response from the server } catch (IOException e) { return false; } HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = null; try { instream = entity.getContent(); @SuppressWarnings("resource") java.util.Scanner s = new java.util.Scanner(instream).useDelimiter("\\A"); // parse the response String responseString = s.hasNext() ? s.next() : ""; instream.close(); return responseString.contains("\"valid\":true"); // if the license is valid, return true, else false } catch (IllegalStateException | IOException e) { return false; } } return false; }
From source file:Onlinedata.MainSendRequest.java
public void downloadData(String filename) { downloadurl = baseurl + filename;/*w ww . j a va 2 s . c om*/ try { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(downloadurl); CloseableHttpResponse response = httpclient.execute(httpget); try { response = httpclient.execute(httpget); HttpEntity serverEntity = response.getEntity(); if (serverEntity != null) { System.out.println("Found file at adress: " + downloadurl); long len = serverEntity.getContentLength(); System.out.println("Length is " + len); download = EntityUtils.toString(serverEntity); System.out.println(download); } } catch (IOException | ParseException ex) { Logger.getLogger(MainSendRequest.class.getName()).log(Level.SEVERE, null, ex); } finally { response.close(); } httpclient.close(); } catch (IOException ex) { Logger.getLogger(MainSendRequest.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.epics.archiverappliance.retrieval.channelarchiver.XMLRPCClient.java
/** * Internal method to make a XML_RPC post call and call the SAX handler on the returned document. * @param serverURL The Server URL/*from w w w.j a va 2 s .c o m*/ * @param handler DefaultHandler * @param postEntity StringEntity * @throws IOException   * @throws SAXException   */ private static void doHTTPPostAndCallSAXHandler(String serverURL, DefaultHandler handler, StringEntity postEntity) throws IOException, SAXException { logger.debug("Executing doHTTPPostAndCallSAXHandler with the server URL " + serverURL); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost postMethod = new HttpPost(serverURL); postMethod.addHeader("Content-Type", "text/xml"); postMethod.setEntity(postEntity); logger.debug("Executing the HTTP POST" + serverURL); HttpResponse response = httpclient.execute(postMethod); HttpEntity entity = response.getEntity(); if (entity != null) { logger.debug("Obtained a HTTP entity of length " + entity.getContentLength()); try (InputStream is = entity.getContent()) { SAXParserFactory sfac = SAXParserFactory.newInstance(); sfac.setNamespaceAware(false); sfac.setValidating(false); SAXParser parser = sfac.newSAXParser(); parser.parse(is, handler); } catch (ParserConfigurationException pex) { throw new IOException(pex); } } else { throw new IOException("HTTP response did not have an entity associated with it"); } }
From source file:com.brett.http.geo.baidu.GeoRequestHttpClient.java
public static JsonNode geoAcquire(String city) 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 a v a 2s. com*/ String address = URLEncoder.encode(city, "utf-8"); String url = "http://api.map.baidu.com/geocoder/v2/?address={address}&output=json&ak=E4805d16520de693a3fe707cdc962045"; url = url.replaceFirst("\\{address\\}", address); 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://developer.baidu.com/map/index.php?title=webapi/guide/webservice-geocoding"); 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(HtmlDecoder.decode(responseBody)); 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)); // {"status":0,"result":{"location":{"lng":116.30783584945,"lat":40.056876296398},"precise":1,"confidence":80,"level":"\u5546\u52a1\u5927\u53a6"}} JsonNode root = mapper.readTree(responseBody); System.out.println("result : " + city + " = " + root.get("result")); return root; } finally { httpclient.close(); } }
From source file:org.fcrepo.camel.indexing.triplestore.integration.TestUtils.java
/** * Get data from the provided URL/* w w w. j ava2s . c o m*/ */ public static InputStream httpGet(final String url) throws Exception { final CloseableHttpClient httpClient = HttpClients.createDefault(); final HttpGet get = new HttpGet(url); return httpClient.execute(get).getEntity().getContent(); }
From source file:org.smartloli.kafka.eagle.common.util.HttpClientUtils.java
/** * Send request by get method.//from www . j a v a 2s .c o m * * @param uri: * http://ip:port/demo?httpcode=200&name=smartloli */ public static String doGet(String uri) { String result = ""; try { CloseableHttpClient client = null; CloseableHttpResponse response = null; try { HttpGet httpGet = new HttpGet(uri); client = HttpClients.createDefault(); response = client.execute(httpGet); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); } finally { if (response != null) { response.close(); } if (client != null) { client.close(); } } } catch (Exception e) { e.printStackTrace(); LOG.error("Do get request has error, msg is " + e.getMessage()); } return result; }
From source file:Logica.prueba.java
public prueba() { cliente = HttpClients.createDefault(); post = new HttpPost(url); post.setHeader("Content-type", "application/json"); try {//from w ww. ja va 2 s . com key = getSessionKey(); } catch (UnsupportedEncodingException ex) { Logger.getLogger(prueba.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.bluehermit.apps.module.soap.client.HttpClientHelperImpl.java
public String post(String target, String message) throws Exception { String responeMessage = null; CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*w w w .j av a2 s . co m*/ HttpPost httppost = new HttpPost(target); httppost.setHeader("Content-Type", "text/xml"); httppost.setEntity(new StringEntity(message)); System.out.println("Executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to bother about connection release if (entity != null) { InputStream instream = entity.getContent(); try { responeMessage = IOUtils.toString(instream, "UTF-8"); // do something useful with the response } catch (IOException ex) { // In case of an IOException the connection will be released // back to the connection manager automatically throw ex; } finally { // Closing the input stream will trigger connection release instream.close(); } } } finally { response.close(); } } finally { httpclient.close(); } return responeMessage; }
From source file:ch.asadzia.cognitive.SituationAnalysis.java
public ServiceResult process() { HttpClient httpclient = HttpClients.createDefault(); try {/* w w w. java2 s .co m*/ URIBuilder builder = new URIBuilder("https://api.projectoxford.ai/vision/v1.0/analyze"); builder.setParameter("visualFeatures", "Categories,Tags,Description,Faces,Adult"); URI uri = builder.build(); HttpPost request = new HttpPost(uri); request.setHeader("Content-Type", "application/octet-stream"); request.setHeader("Ocp-Apim-Subscription-Key", apikey); // Request body FileEntity reqEntity = new FileEntity(imageData); request.setEntity(reqEntity); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { String responseStr = EntityUtils.toString(entity); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.err.println(responseStr); return null; } ServiceResult result = translateSituation(responseStr); System.out.println(responseStr); return result; } } catch (Exception e) { System.out.println(e.getMessage()); } return null; }