List of usage examples for javax.net.ssl HttpsURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:org.openadaptor.util.PropertiesPoster.java
/** * Utility method which will attempt to POST the supplied properties information to the supplied URL. * /*from w w w . j a va 2 s . c o m*/ * This method currently contains an all trusting trust manager for use with https. This will be replaced with a more * secure trust manager which will use a cert store. * * @param registrationURL * @param properties * @throws Exception */ protected static void syncPostHttp(String registrationURL, Properties properties) throws Exception { URL url = new URL(registrationURL); String postData = generatePOSTData(properties); log.debug("Protocol: " + url.getProtocol()); if (url.getProtocol().equals("https")) { // https connection // TODO: Replace this all trusting manager with one that uses a cert store // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection secureConnection = null; HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); secureConnection = (HttpsURLConnection) url.openConnection(); secureConnection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(secureConnection.getOutputStream()); writer.write(postData); writer.flush(); int responseCode = secureConnection.getResponseCode(); if (HttpsURLConnection.HTTP_OK != responseCode) { log.error("\nFailed to register. Response Code " + responseCode + "\nResponse message:" + secureConnection.getResponseMessage() + "\nRegistration URL: " + registrationURL + "\nData: " + generateString(properties)); } BufferedReader br = new BufferedReader(new InputStreamReader(secureConnection.getInputStream())); String line; while ((line = br.readLine()) != null) { log.debug("Returned data: " + line); } writer.close(); br.close(); } else { // Normal http connection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(postData); writer.flush(); int responseCode = connection.getResponseCode(); if (HttpURLConnection.HTTP_OK != responseCode) { log.error("\nFailed to register. Response Code " + responseCode + "\nResponse message:" + connection.getResponseMessage() + "\nRegistration URL: " + registrationURL + "\nData: " + generateString(properties)); } BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = br.readLine()) != null) { log.debug("Returned data: " + line); } writer.close(); br.close(); } }
From source file:org.liberty.android.fantastischmemo.downloader.google.DocumentFactory.java
public static Document createSpreadsheet(String title, String authToken) throws XmlPullParserException, IOException { URL url = new URL("https://www.googleapis.com/drive/v2/files"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoInput(true);//from w w w . jav a2 s .c o m conn.setDoOutput(true); conn.setRequestProperty("Authorization", "Bearer " + authToken); conn.setRequestProperty("Content-Type", "application/json"); String payload = "{\"title\":\"" + title + "\",\"mimeType\":\"application/vnd.google-apps.spreadsheet\"}"; conn.setRequestProperty("Content-Length", "" + payload.length()); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(conn.getOutputStream()); outputStreamWriter.write(payload); outputStreamWriter.close(); if (conn.getResponseCode() / 100 >= 3) { String s = new String(IOUtils.toByteArray(conn.getErrorStream())); throw new RuntimeException(s); } return EntryFactory.getEntryFromDriveApi(Document.class, conn.getInputStream()); }
From source file:com.illusionaryone.BTTVAPIv2.java
@SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String urlAddress) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; URL urlRaw;//from w w w . ja v a 2s . c o m HttpsURLConnection urlConn; String jsonText = ""; try { urlRaw = new URL(urlAddress); urlConn = (HttpsURLConnection) urlRaw.openConnection(); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.addRequestProperty("Content-Type", "application/json"); urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); urlConn.connect(); if (urlConn.getResponseCode() == 200) { inputStream = urlConn.getInputStream(); } else { inputStream = urlConn.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); jsonText = readAll(rd); jsonResult = new JSONObject(jsonText); fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText); } catch (JSONException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText); com.gmt2001.Console.err.printStackTrace(ex); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } catch (Exception ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } } return (jsonResult); }
From source file:eu.siacs.conversations.ui.ServiceBrowserFragment.java
public static boolean exists(String URLName) { X509TrustManager trustManager = new X509TrustManager() { @Override/*from w ww.j a v a 2 s. c o m*/ public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // NOTE : This is where we can calculate the certificate's fingerprint, // show it to the user and throw an exception in case he doesn't like it } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } }; // Create a trust manager that does not validate certificate chains X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager }; // Install the all-trusting trust manager SSLSocketFactory noSSLv3Factory = null; try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom()); } else { noSSLv3Factory = sc.getSocketFactory(); } HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory); } catch (GeneralSecurityException e) { } try { HttpsURLConnection.setFollowRedirects(false); // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) URL url = new URL(URLName); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setSSLSocketFactory(noSSLv3Factory); con.setRequestProperty("Accept-Encoding", ""); //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier()); con.setHostnameVerifier(new NullHostNameVerifier(url.getHost())); con.setRequestMethod("HEAD"); return (con.getResponseCode() == HttpsURLConnection.HTTP_OK); } catch (Exception e) { e.printStackTrace(); return false; } }
From source file:com.scaniatv.TipeeeStreamAPIv1.java
@SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String urlAddress) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; URL urlRaw;/*from w w w. j a v a 2 s . c om*/ HttpsURLConnection urlConn; String jsonText = ""; try { urlRaw = new URL(urlAddress); urlConn = (HttpsURLConnection) urlRaw.openConnection(); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.addRequestProperty("Content-Type", "application/json"); urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); urlConn.connect(); if (urlConn.getResponseCode() == 200) { inputStream = urlConn.getInputStream(); } else { inputStream = urlConn.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); jsonText = readAll(rd); jsonResult = new JSONObject(jsonText); fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText); } catch (JSONException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText); com.gmt2001.Console.debug.println("TipeeeStreamAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.debug.println("TipeeeStreamAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.debug.println("TipeeeStreamAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.debug.println("TipeeeStreamAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.debug.println("TipeeeStreamAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (Exception ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.debug.println("TipeeeStreamAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.debug .println("TipeeeStreamAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } } } return (jsonResult); }
From source file:com.illusionaryone.StreamTipAPI.java
@SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String urlAddress) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; URL urlRaw;/* w w w . j a va 2s . c om*/ HttpsURLConnection urlConn; String jsonText = ""; try { urlRaw = new URL(urlAddress); urlConn = (HttpsURLConnection) urlRaw.openConnection(); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.addRequestProperty("Content-Type", "application/json"); urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); urlConn.connect(); if (urlConn.getResponseCode() == 200) { inputStream = urlConn.getInputStream(); } else { inputStream = urlConn.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); jsonText = readAll(rd); jsonResult = new JSONObject(jsonText); fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText); } catch (JSONException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText); com.gmt2001.Console.debug.println("StreamTipAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.debug.println("StreamTipAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.debug.println("StreamTipAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.debug.println("StreamTipAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.debug.println("StreamTipAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (Exception ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.debug.println("StreamTipAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.debug .println("StreamTipAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } } return (jsonResult); }
From source file:org.openhab.binding.whistle.internal.WhistleBinding.java
static private String GetData(URL obj, String authToken) throws Exception { HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); // add request headers and parameters con.setDoOutput(true);/* w w w .j a va 2s . c om*/ con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("User-Agent", "WhistleApp/102 (iPhone; iOS 7.0.4; Scale/2.00)"); con.setRequestProperty("X-Whistle-AuthToken", authToken); // System.out.println("Response Code : " + con.getResponseCode()); if (con.getResponseCode() != 200) { logger.error("Failed to get requested data, response code: '{}'", con.getResponseCode()); return null; } // Get the data BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String response = in.readLine(); in.close(); return response; }
From source file:org.liberty.android.fantastischmemo.downloader.google.FolderFactory.java
public static Folder createFolder(String title, String authToken) throws XmlPullParserException, IOException { URL url = new URL("https://www.googleapis.com/drive/v2/files"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoInput(true);//from w w w.j a v a 2 s.c om conn.setDoOutput(true); conn.setRequestProperty("Authorization", "Bearer " + authToken); conn.setRequestProperty("Content-Type", "application/json"); // Used to calculate the content length of the multi part String payload = "{\"title\":\"" + title + "\",\"mimeType\":\"application/vnd.google-apps.folder\"}"; conn.setRequestProperty("Content-Length", "" + payload.length()); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(conn.getOutputStream()); outputStreamWriter.write(payload); outputStreamWriter.close(); if (conn.getResponseCode() / 100 >= 3) { String s = new String(IOUtils.toByteArray(conn.getErrorStream())); throw new RuntimeException(s); } return EntryFactory.getEntryFromDriveApi(Folder.class, conn.getInputStream()); }
From source file:com.illusionaryone.TwitchTMIv1.java
@SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String urlAddress, boolean isArray) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; URL urlRaw;//from w ww . j av a2 s .co m HttpsURLConnection urlConn; String jsonText = ""; try { urlRaw = new URL(urlAddress); urlConn = (HttpsURLConnection) urlRaw.openConnection(); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.addRequestProperty("Content-Type", "application/json"); urlConn.addRequestProperty("Accept", "application/vnd.github.v3+json"); urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); urlConn.connect(); if (urlConn.getResponseCode() == 200) { inputStream = urlConn.getInputStream(); } else { inputStream = urlConn.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); jsonText = readAll(rd); if (isArray) { jsonResult = new JSONObject("{ \"array\": " + jsonText + " }"); } else { jsonResult = new JSONObject(jsonText); } fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText); } catch (JSONException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText); com.gmt2001.Console.err.println("TwitchTMIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.err.println("TwitchTMIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.err.println("TwitchTMIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.err.println("TwitchTMIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.println("TwitchTMIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (Exception ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.err.println("TwitchTMIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.println("TwitchTMIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } } return (jsonResult); }
From source file:ro.fortsoft.matilda.util.RecaptchaUtils.java
public static boolean verify(String recaptchaResponse, String secret) { if (StringUtils.isNullOrEmpty(recaptchaResponse)) { return false; }//from w w w . j a va2s . co m boolean result = false; try { URL url = new URL("https://www.google.com/recaptcha/api/siteverify"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); // add request header connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String postParams = "secret=" + secret + "&response=" + recaptchaResponse; // log.debug("Post parameters '{}'", postParams); // send post request connection.setDoOutput(true); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(postParams); outputStream.flush(); outputStream.close(); int responseCode = connection.getResponseCode(); log.debug("Response code '{}'", responseCode); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // print result log.debug("Response '{}'", response.toString()); // parse JSON response and return 'success' value ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.readTree(response.toString()); JsonNode nameNode = rootNode.path("success"); result = nameNode.asBoolean(); } catch (Exception e) { log.error(e.getMessage(), e); } return result; }