List of usage examples for javax.net.ssl HttpsURLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:br.com.intelidev.dao.userDao.java
/** * Run the web service request/*from ww w. j a v a 2s.c o m*/ * @param username * @param password * @return */ public boolean login_acess(String username, String password) { HttpsURLConnection conn = null; boolean bo_return = false; try { // Create url to the Device Cloud server for a given web service request URL url = new URL("https://devicecloud.digi.com/ws/sci"); conn = (HttpsURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("GET"); // Build authentication string String userpassword = username + ":" + password; // can change this to use a different base64 encoder String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim(); // set request headers conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization); // Get input stream from response and convert to String InputStream is = conn.getInputStream(); Scanner isScanner = new Scanner(is); StringBuffer buf = new StringBuffer(); while (isScanner.hasNextLine()) { buf.append(isScanner.nextLine() + "\n"); } //String responseContent = buf.toString(); // add line returns between tags to make it a bit more readable //responseContent = responseContent.replaceAll("><", ">\n<"); // Output response to standard out //System.out.println(responseContent); bo_return = true; } catch (Exception e) { // Print any exceptions that occur System.out.println("br.com.intelidev.dao.userDao.login_acess() Error: " + e); bo_return = false; //e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); if (bo_return) { System.out.println("Conectou "); } else { System.out.println("No conectou "); } } return bo_return; }
From source file:org.georchestra.console.ReCaptchaV2.java
/** * * @param url/* ww w. j a va 2 s .com*/ * @param privateKey * @param gRecaptchaResponse * * @return true if validaded on server side by google, false in case of error or if an exception occurs */ public boolean isValid(String url, String privateKey, String gRecaptchaResponse) { boolean isValid = false; try { URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); // add request header con.setRequestMethod("POST"); String postParams = "secret=" + privateKey + "&response=" + gRecaptchaResponse; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(postParams); wr.flush(); wr.close(); if (LOG.isDebugEnabled()) { int responseCode = con.getResponseCode(); LOG.debug("\nSending 'POST' request to URL : " + url); LOG.debug("Post parameters : " + postParams); LOG.debug("Response Code : " + responseCode); } // getResponse BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result LOG.debug(response.toString()); JSONObject captchaResponse; try { captchaResponse = new JSONObject(response.toString()); if (captchaResponse.getBoolean("success")) { isValid = true; } else { // Error in response LOG.info("The user response to recaptcha is not valid. The error message is '" + captchaResponse.getString("error-codes") + "' - see Error Code Reference at https://developers.google.com/recaptcha/docs/verify."); } } catch (JSONException e) { // Error in response LOG.error("Error while parsing ReCaptcha JSON response", e); } } catch (IOException e) { LOG.error("An error occured when trying to contact google captchaV2", e); } return isValid; }
From source file:org.jembi.rhea.rapidsms.GenerateORU_R01Alert.java
public String callQueryFacility(String msg) throws IOException, TransformerFactoryConfigurationError, TransformerException { // Setup connection URL url = new URL(hostname + "/ws/rest/v1/alerts"); System.out.println("full url " + url); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setDoOutput(true);//from w w w. jav a 2 s. c om conn.setRequestMethod("POST"); conn.setDoInput(true); // This is important to get the connection to use our trusted // certificate conn.setSSLSocketFactory(sslFactory); addHTTPBasicAuthProperty(conn); // conn.setConnectTimeout(timeOut); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); log.error("body" + msg); out.write(msg); out.close(); conn.connect(); // Test response code if (conn.getResponseCode() != 200) { throw new IOException(conn.getResponseMessage()); } String result = convertInputStreamToString(conn.getInputStream()); conn.disconnect(); return result; }
From source file:pack_test.Get_stream.java
/** * Run the web service request/*from w w w. j a v a2 s . c o m*/ */ //public static void main(String[] args) { public void main() { HttpsURLConnection conn = null; try { // Create url to the Device Cloud server for a given web service request URL url = new URL( "https://devicecloud.digi.com/ws/v1/streams/history/00000000-00000000-00409DFF-FF6064F8/xbee.analog/[00:13:A2:00:40:E6:5A:88]!/AD1"); conn = (HttpsURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("GET"); // Build authentication string String userpassword = username + ":" + password; // can change this to use a different base64 encoder String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim(); // set request headers conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization); // Get input stream from response and convert to String InputStream is = conn.getInputStream(); Scanner isScanner = new Scanner(is); StringBuffer buf = new StringBuffer(); while (isScanner.hasNextLine()) { buf.append(isScanner.nextLine() + "\n"); } String responseContent = buf.toString(); // add line returns between tags to make it a bit more readable responseContent = responseContent.replaceAll("><", ">\n<"); // Output response to standard out System.out.println(responseContent); } catch (Exception e) { // Print any exceptions that occur e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } }
From source file:org.wso2.carbon.appmgt.sample.deployer.http.HttpHandler.java
/** * This method is used to do a https post request * * @param url request url/*from w ww .j a va 2s. c om*/ * @param payload Content of the post request * @param sessionId sessionId for authentication * @param contentType content type of the post request * @return response * @throws java.io.IOException - Throws this when failed to fulfill a https post request */ public String doPostHttps(String url, String payload, String sessionId, String contentType) throws IOException { URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); if (!sessionId.equals("")) { con.setRequestProperty("Cookie", "JSESSIONID=" + sessionId); } if (!contentType.equals("")) { con.setRequestProperty("Content-Type", contentType); } con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(payload); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); if (sessionId.equals("")) { String session_id = response.substring((response.lastIndexOf(":") + 3), (response.lastIndexOf("}") - 2)); return session_id; } else if (sessionId.equals("header")) { return con.getHeaderField("Set-Cookie"); } return response.toString(); } return null; }
From source file:org.wso2.carbon.identity.authenticator.mepin.MepinTransactions.java
protected String getTransaction(String url, String transactionId, String clientId, String username, String password) throws IOException { log.debug("Started handling transaction creation"); String authStr = username + ":" + password; String encoding = new String(Base64.encodeBase64(authStr.getBytes())); HttpsURLConnection connection = null; String responseString = ""; url = url + "?transaction_id=" + transactionId + "&client_id=" + clientId; try {//www . ja va 2s. co m connection = (HttpsURLConnection) new URL(url).openConnection(); connection.setRequestMethod(MepinConstants.HTTP_GET); connection.setRequestProperty(MepinConstants.HTTP_ACCEPT, MepinConstants.HTTP_CONTENT_TYPE); connection.setRequestProperty(MepinConstants.HTTP_AUTHORIZATION, MepinConstants.HTTP_AUTHORIZATION_BASIC + encoding); String response = ""; int statusCode = connection.getResponseCode(); InputStream is; if ((statusCode == 200) || (statusCode == 201)) { is = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { responseString += output; } br.close(); } else { is = connection.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { responseString += output; } br.close(); if (log.isDebugEnabled()) { log.debug("MePIN Status Response: " + response); } return MepinConstants.FAILED; } } catch (IOException e) { throw new IOException(e.getMessage(), e); } finally { connection.disconnect(); } return responseString; }
From source file:de.btobastian.javacord.entities.impl.ImplUser.java
@Override public Future<byte[]> getAvatarAsByteArray(FutureCallback<byte[]> callback) { ListenableFuture<byte[]> future = api.getThreadPool().getListeningExecutorService() .submit(new Callable<byte[]>() { @Override// w w w.ja va2 s.c om public byte[] call() throws Exception { logger.debug("Trying to get avatar from user {}", ImplUser.this); if (avatarId == null) { logger.debug("User {} seems to have no avatar. Returning empty array!", ImplUser.this); return new byte[0]; } URL url = new URL( "https://discordapp.com/api/users/" + id + "/avatars/" + avatarId + ".jpg"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.setRequestProperty("User-Agent", Javacord.USER_AGENT); InputStream in = new BufferedInputStream(conn.getInputStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int n; while (-1 != (n = in.read(buf))) { out.write(buf, 0, n); } out.close(); in.close(); byte[] avatar = out.toByteArray(); logger.debug("Got avatar from user {} (size: {})", ImplUser.this, avatar.length); return avatar; } }); if (callback != null) { Futures.addCallback(future, callback); } return future; }
From source file:com.gmt2001.TwitchAPIv2.java
private JSONObject GetData(request_type type, String url, String post, String oauth) { JSONObject j = new JSONObject(); try {// ww w . ja v a2 s . c o m URL u = new URL(url); HttpsURLConnection c = (HttpsURLConnection) u.openConnection(); c.addRequestProperty("Accept", header_accept); if (!clientid.isEmpty()) { c.addRequestProperty("Client-ID", clientid); } if (!oauth.isEmpty()) { c.addRequestProperty("Authorization", "OAuth " + oauth); } c.setRequestMethod(type.name()); c.setUseCaches(false); c.setDefaultUseCaches(false); c.setConnectTimeout(timeout); c.connect(); if (!post.isEmpty()) { IOUtils.write(post, c.getOutputStream()); } String content; if (c.getResponseCode() == 200) { content = IOUtils.toString(c.getInputStream(), c.getContentEncoding()); } else { content = IOUtils.toString(c.getErrorStream(), c.getContentEncoding()); } j = new JSONObject(content); j.put("_success", true); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", c.getResponseCode()); j.put("_exception", ""); j.put("_exceptionMessage", ""); } catch (MalformedURLException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "MalformedURLException"); j.put("_exceptionMessage", ex.getMessage()); } catch (SocketTimeoutException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "SocketTimeoutException"); j.put("_exceptionMessage", ex.getMessage()); } catch (IOException ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); } catch (Exception ex) { j.put("_success", false); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_exception", "Exception [" + ex.getClass().getName() + "]"); j.put("_exceptionMessage", ex.getMessage()); } return j; }
From source file:com.alvexcore.share.ShareExtensionRegistry.java
public ExtensionUpdateInfo checkForUpdates(String extensionId, String shareId, Map<String, String> shareHashes, String shareVersion, String repoId, Map<String, String> repoHashes, String repoVersion, String licenseId) throws Exception { // search for extension DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance(); xmlFact.setNamespaceAware(true);/*from w w w .j ava2 s .co m*/ xmlBuilder = xmlFact.newDocumentBuilder(); // build query Document queryXML = xmlBuilder.newDocument(); Element rootElement = queryXML.createElement("extension"); queryXML.appendChild(rootElement); Element el = queryXML.createElement("license-id"); el.appendChild(queryXML.createTextNode(licenseId)); rootElement.appendChild(el); el = queryXML.createElement("id"); el.appendChild(queryXML.createTextNode(extensionId)); rootElement.appendChild(el); el = queryXML.createElement("share-version"); el.appendChild(queryXML.createTextNode(shareVersion)); rootElement.appendChild(el); el = queryXML.createElement("repo-version"); el.appendChild(queryXML.createTextNode(repoVersion)); rootElement.appendChild(el); el = queryXML.createElement("share-id"); el.appendChild(queryXML.createTextNode(shareId)); rootElement.appendChild(el); el = queryXML.createElement("repo-id"); el.appendChild(queryXML.createTextNode(repoId)); rootElement.appendChild(el); el = queryXML.createElement("share-files"); rootElement.appendChild(el); for (String fileName : shareHashes.keySet()) { Element fileElem = queryXML.createElement("file"); fileElem.setAttribute("md5hash", shareHashes.get(fileName)); fileElem.appendChild(queryXML.createTextNode(fileName)); el.appendChild(fileElem); } el = queryXML.createElement("repo-files"); rootElement.appendChild(el); for (String fileName : repoHashes.keySet()) { Element fileElem = queryXML.createElement("file"); fileElem.setAttribute("md5hash", repoHashes.get(fileName)); fileElem.appendChild(queryXML.createTextNode(fileName)); el.appendChild(fileElem); } // query server try { URL url = new URL( "https://update.alvexhq.com:443/alfresco/s/api/alvex/extension/" + extensionId + "/update"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); // disable host verification conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); TransformerFactory.newInstance().newTransformer().transform(new DOMSource(queryXML), new StreamResult(wr)); wr.close(); // get response Document responseXML = xmlBuilder.parse(conn.getInputStream()); XPath xpath = XPathFactory.newInstance().newXPath(); // get version String repoLatestVersion = ((Node) xpath.evaluate("/extension/repo-version/text()", responseXML, XPathConstants.NODE)).getNodeValue(); String shareLatestVersion = ((Node) xpath.evaluate("/extension/share-version/text()", responseXML, XPathConstants.NODE)).getNodeValue(); NodeList nl = (NodeList) xpath.evaluate("/extension/repo-files/file", responseXML, XPathConstants.NODESET); Map<String, Boolean> repoFiles = new HashMap<String, Boolean>(nl.getLength()); for (int i = 0; i < nl.getLength(); i++) repoFiles.put(nl.item(i).getTextContent(), "ok".equals(nl.item(i).getAttributes().getNamedItem("status").getNodeValue())); nl = (NodeList) xpath.evaluate("/extension/share-files/file", responseXML, XPathConstants.NODESET); Map<String, Boolean> shareFiles = new HashMap<String, Boolean>(nl.getLength()); for (int i = 0; i < nl.getLength(); i++) shareFiles.put(nl.item(i).getTextContent(), "ok".equals(nl.item(i).getAttributes().getNamedItem("status").getNodeValue())); String motd = ((Node) xpath.evaluate("/extension/motd/text()", responseXML, XPathConstants.NODE)) .getNodeValue(); return new ExtensionUpdateInfo(extensionId, repoVersion, shareVersion, repoLatestVersion, shareLatestVersion, repoFiles, shareFiles, motd); } catch (Exception e) { return new ExtensionUpdateInfo(extensionId, repoVersion, shareVersion, "", "", new HashMap<String, Boolean>(), new HashMap<String, Boolean>(), ""); } }
From source file:com.esri.geoevent.test.performance.bds.BdsEventConsumer.java
private int getMsLayerCount(String url) { int cnt = -1; try {/*from w w w.j a v a 2s .com*/ URL obj = new URL(url + "/query"); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add request header con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); con.setRequestProperty("Accept", "text/plain"); String urlParameters = "where=" + URLEncoder.encode("1=1", "UTF-8") + "&returnCountOnly=" + URLEncoder.encode("true", "UTF-8") + "&f=" + URLEncoder.encode("json", "UTF-8"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result String jsonString = response.toString(); JSONTokener tokener = new JSONTokener(jsonString); JSONObject root = new JSONObject(tokener); cnt = root.getInt("count"); } catch (Exception e) { cnt = -2; } finally { return cnt; } }