List of usage examples for javax.net.ssl HttpsURLConnection connect
public abstract void connect() throws IOException;
From source file:com.microsoft.speech.tts.OxfordAuthentication.java
private void HttpPost(String AccessTokenUri, String requestDetails) { InputStream inSt = null;/*from ww w.j a v a 2s . com*/ HttpsURLConnection webRequest = null; this.token = null; //Prepare OAuth request try { URL url = new URL(AccessTokenUri); webRequest = (HttpsURLConnection) url.openConnection(); webRequest.setDoInput(true); webRequest.setDoOutput(true); webRequest.setConnectTimeout(5000); webRequest.setReadTimeout(5000); webRequest.setRequestProperty("content-type", "application/x-www-form-urlencoded"); webRequest.setRequestMethod("POST"); byte[] bytes = requestDetails.getBytes(); webRequest.setRequestProperty("content-length", String.valueOf(bytes.length)); webRequest.connect(); DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream()); dop.write(bytes); dop.flush(); dop.close(); inSt = webRequest.getInputStream(); InputStreamReader in = new InputStreamReader(inSt); BufferedReader bufferedReader = new BufferedReader(in); StringBuffer strBuffer = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { strBuffer.append(line); } bufferedReader.close(); in.close(); inSt.close(); webRequest.disconnect(); // parse the access token from the json format String result = strBuffer.toString(); JSONObject jsonRoot = new JSONObject(result); this.token = new OxfordAccessToken(); if (jsonRoot.has("access_token")) { this.token.access_token = jsonRoot.getString("access_token"); } if (jsonRoot.has("token_type")) { this.token.token_type = jsonRoot.getString("token_type"); } if (jsonRoot.has("expires_in")) { this.token.expires_in = jsonRoot.getString("expires_in"); } if (jsonRoot.has("scope")) { this.token.scope = jsonRoot.getString("scope"); } } catch (Exception e) { Log.e(LOG_TAG, "Exception error", e); } }
From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java
private String getPEMCertificateFromServer(String host) { HttpsURLConnection connection = null; try {/*from w w w. j a va 2 s .co m*/ URL url = new URL(host); connection = (HttpsURLConnection) url.openConnection(); connection.setHostnameVerifier(hostnameVerifier); connection.setSSLSocketFactory(generateSSLContextWhichAcceptAllSSLCertificats()); connection.connect(); java.security.cert.Certificate[] cert = connection.getServerCertificates(); connection.disconnect(); byte[] by = ((X509Certificate) cert[0]).getEncoded(); if (by.length != 0) { return BEGIN_CERT + Base64.getEncoder().encodeToString(by) + END_CERT; } } catch (MalformedURLException e) { if (!informConnectionManager(ConnectionManager.MALFORMED_URL_EXCEPTION)) { logger.error("A MalformedURLException occurred: ", e); } } catch (IOException e) { short code = ConnectionManager.GENERAL_EXCEPTION; if (e instanceof java.net.ConnectException) { code = ConnectionManager.CONNECTION_EXCEPTION; } else if (e instanceof java.net.UnknownHostException) { code = ConnectionManager.UNKNOWN_HOST_EXCEPTION; } if (!informConnectionManager(code) || code == -1) { logger.error("An IOException occurred: ", e); } } catch (CertificateEncodingException e) { logger.error("A CertificateEncodingException occurred: ", e); } finally { if (connection != null) { connection.disconnect(); } } return null; }
From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java
public String[] callGet(String stringUrl) { try {//w w w . ja v a2s.c o m // Setup connection URL url = new URL(stringUrl); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); // This is important to get the connection to use our trusted // certificate conn.setSSLSocketFactory(sslFactory); addHTTPBasicAuthProperty(conn); //conn.setConnectTimeout(timeOut); // bug fixing for SSL error, this is a temporary fix, need to find a // long term one conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); // printHttpsCert(conn); conn.connect(); int code = conn.getResponseCode(); if (code >= 200 && code < 300) { String result = IOUtils.toString(conn.getInputStream()); conn.disconnect(); return new String[] { code + "", result }; } else { conn.disconnect(); return new String[] { code + "", "Server returned " + code + " response code" }; } } catch (MalformedURLException e) { e.printStackTrace(); log.error("MalformedURLException while callGet " + e.getMessage()); return new String[] { 400 + "", e.getMessage() }; } catch (IOException e) { e.printStackTrace(); log.error("IOException while callGet " + e.getMessage()); return new String[] { 600 + "", e.getMessage() }; } }
From source file:de.bps.webservices.clients.onyxreporter.OnyxReporterConnector.java
private boolean isServiceAvailable(String target) { HostnameVerifier hv = new HostnameVerifier() { @Override/*from w w w . j av a 2 s.c o m*/ public boolean verify(String urlHostName, SSLSession session) { if (urlHostName.equals(session.getPeerHost())) { return true; } else { return false; } } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); try { URL url = new URL(target + "?wsdl"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); if (con instanceof HttpsURLConnection) { HttpsURLConnection sslconn = (HttpsURLConnection) con; SSLContext context = SSLContext.getInstance("SSL"); context.init(SSLConfigurationModule.getKeyManagers(), SSLConfigurationModule.getTrustManagers(), new java.security.SecureRandom()); sslconn.setSSLSocketFactory(context.getSocketFactory()); sslconn.connect(); if (sslconn.getResponseCode() == HttpURLConnection.HTTP_OK) { sslconn.disconnect(); return true; } } else { con.connect(); if (con.getResponseCode() == HttpURLConnection.HTTP_OK) { con.disconnect(); return true; } } } catch (Exception e) { Tracing.createLoggerFor(getClass()).error("Error while trying to connect to webservice: " + target, e); } return false; }
From source file:com.google.android.apps.santatracker.presentquest.PlacesIntentService.java
private ArrayList<LatLng> fetchPlacesFromAPI(LatLng center, int radius) { ArrayList<LatLng> places = new ArrayList<>(); radius = Math.min(radius, 50000); // Max accepted radius is 50km. try {// w w w . ja va 2 s.c o m InputStream is = null; URL url = new URL(getString(R.string.places_api_url) + "?location=" + center.latitude + "," + center.longitude + "&radius=" + radius); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); // Pass package name and signature as part of request String packageName = getPackageName(); String signature = getAppSignature(); conn.setRequestProperty("X-App-Package", packageName); conn.setRequestProperty("X-App-Signature", signature); conn.connect(); int response = conn.getResponseCode(); if (response != 200) { Log.e(TAG, "Places API HTTP error: " + response + " / " + url); } else { BufferedReader reader; StringBuilder builder = new StringBuilder(); reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); for (String line; (line = reader.readLine()) != null;) { builder.append(line); } JSONArray resultsJson = (new JSONObject(builder.toString())).getJSONArray("results"); for (int i = 0; i < resultsJson.length(); i++) { JSONObject latLngJson = ((JSONObject) resultsJson.get(i)).getJSONObject("geometry") .getJSONObject("location"); places.add(new LatLng(latLngJson.getDouble("lat"), latLngJson.getDouble("lng"))); } } } catch (Exception e) { Log.e(TAG, "Exception parsing places API: " + e.toString()); } return places; }
From source file:com.tune.reporting.base.service.TuneServiceProxy.java
/** * Post request to TUNE Service API Service * * @return Boolean True if successful posting request, else False. * @throws TuneSdkException If error within SDK. *///from w ww.j a v a 2 s . com protected boolean postRequest() throws TuneSdkException { URL url = null; HttpsURLConnection conn = null; try { url = new URL(this.uri); } catch (MalformedURLException ex) { throw new TuneSdkException(String.format("Problems executing request: %s: %s: '%s'", this.uri, ex.getClass().toString(), ex.getMessage()), ex); } try { // connect to the server over HTTPS and submit the payload conn = (HttpsURLConnection) url.openConnection(); // Create the SSL connection SSLContext sc; sc = SSLContext.getInstance("TLS"); sc.init(null, null, new java.security.SecureRandom()); conn.setSSLSocketFactory(sc.getSocketFactory()); conn.setRequestMethod("GET"); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.connect(); // Gets the status code from an HTTP response message. final int responseHttpCode = conn.getResponseCode(); // Returns an unmodifiable Map of the header fields. // The Map keys are Strings that represent the response-header // field names. Each Map value is an unmodifiable List of Strings // that represents the corresponding field values. final Map<String, List<String>> responseHeaders = conn.getHeaderFields(); final String requestUrl = url.toString(); // Gets the HTTP response message, if any, returned along // with the response code from a server. String responseRaw = conn.getResponseMessage(); // Pull entire JSON raw response BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); responseRaw = sb.toString(); // decode to JSON JSONObject responseJson = new JSONObject(responseRaw); this.response = new TuneServiceResponse(responseRaw, responseJson, responseHttpCode, responseHeaders, requestUrl.toString()); } catch (Exception ex) { throw new TuneSdkException(String.format("Problems executing request: %s: '%s'", ex.getClass().toString(), ex.getMessage()), ex); } return true; }
From source file:com.gloriouseggroll.LastFMAPI.java
@SuppressWarnings({ "null", "SleepWhileInLoop", "UseSpecificCatch" }) private JSONObject GetData(request_type type, String url, String post) { Date start = new Date(); Date preconnect = start;/*from ww w.j av a 2 s . c o m*/ Date postconnect = start; Date prejson = start; Date postjson = start; JSONObject j = new JSONObject("{}"); BufferedInputStream i = null; String rawcontent = ""; int available = 0; int responsecode = 0; long cl = 0; try { URL u = new URL(url); HttpsURLConnection c = (HttpsURLConnection) u.openConnection(); c.setRequestMethod(type.name()); c.setUseCaches(false); c.setDefaultUseCaches(false); c.setConnectTimeout(5000); c.setReadTimeout(5000); c.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 QuorraBot/2015"); c.setRequestProperty("Content-Type", "application/json-rpc"); c.setRequestProperty("Content-length", "0"); if (!post.isEmpty()) { c.setDoOutput(true); } preconnect = new Date(); c.connect(); postconnect = new Date(); if (!post.isEmpty()) { try (BufferedOutputStream o = new BufferedOutputStream(c.getOutputStream())) { IOUtils.write(post, o); } } String content; cl = c.getContentLengthLong(); responsecode = c.getResponseCode(); if (c.getResponseCode() == 200) { i = new BufferedInputStream(c.getInputStream()); } else { i = new BufferedInputStream(c.getErrorStream()); } /* * if (i != null) { available = i.available(); * * while (available == 0 && (new Date().getTime() - * postconnect.getTime()) < 450) { Thread.sleep(500); available = * i.available(); } * * if (available == 0) { i = new * BufferedInputStream(c.getErrorStream()); * * if (i != null) { available = i.available(); } } } * * if (available == 0) { content = "{}"; } else { content = * IOUtils.toString(i, c.getContentEncoding()); } */ content = IOUtils.toString(i, c.getContentEncoding()); rawcontent = content; prejson = new Date(); 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("_available", available); j.put("_exception", ""); j.put("_exceptionMessage", ""); j.put("_content", content); postjson = new Date(); } catch (JSONException ex) { if (ex.getMessage().contains("A JSONObject text must begin with")) { j = new JSONObject("{}"); j.put("_success", true); j.put("_type", type.name()); j.put("_url", url); j.put("_post", post); j.put("_http", 0); j.put("_available", available); j.put("_exception", "MalformedJSONData (HTTP " + responsecode + ")"); j.put("_exceptionMessage", ""); j.put("_content", rawcontent); } else { com.gmt2001.Console.err.logStackTrace(ex); } } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } 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("_available", available); j.put("_exception", "MalformedURLException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (Quorrabot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } 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("_available", available); j.put("_exception", "SocketTimeoutException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (Quorrabot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } 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("_available", available); j.put("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (Quorrabot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } 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("_available", available); j.put("_exception", "Exception [" + ex.getClass().getName() + "]"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (Quorrabot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } if (i != null) { try { i.close(); } 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("_available", available); j.put("_exception", "IOException"); j.put("_exceptionMessage", ex.getMessage()); j.put("_content", ""); if (Quorrabot.enableDebugging) { com.gmt2001.Console.err.printStackTrace(ex); } else { com.gmt2001.Console.err.logStackTrace(ex); } } } if (Quorrabot.enableDebugging) { com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData Timers " + (preconnect.getTime() - start.getTime()) + " " + (postconnect.getTime() - start.getTime()) + " " + (prejson.getTime() - start.getTime()) + " " + (postjson.getTime() - start.getTime()) + " " + start.toString() + " " + postjson.toString()); com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData Exception " + j.getString("_exception") + " " + j.getString("_exceptionMessage")); com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData HTTP/Available " + j.getInt("_http") + "(" + responsecode + ")/" + j.getInt("_available") + "(" + cl + ")"); com.gmt2001.Console.out.println(">>>[DEBUG] LastFMAPI.GetData RawContent[0,100] " + j.getString("_content").substring(0, Math.min(100, j.getString("_content").length()))); } return j; }
From source file:ovh.tgrhavoc.aibot.auth.YggdrasilAuthService.java
private JSONObject post(String targetURL, JSONObject request, ProxyData proxy) throws IOException { Proxy wrappedProxy = wrapProxy(proxy); String requestValue = request.toJSONString(); HttpsURLConnection connection = null; try {// ww w . jav a2s.com URL url = new URL(targetURL); if (wrappedProxy != null) connection = (HttpsURLConnection) url.openConnection(wrappedProxy); else connection = (HttpsURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", Integer.toString(requestValue.length())); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setReadTimeout(3000); connection.setConnectTimeout(3000); connection.connect(); /*Certificate[] certs = connection.getServerCertificates(); byte[] bytes = new byte[294]; DataInputStream dis = new DataInputStream(Session.class.getResourceAsStream("/minecraft.key")); dis.readFully(bytes); dis.close(); Certificate c = certs[0]; PublicKey pk = c.getPublicKey(); byte[] data = pk.getEncoded(); for(int i = 0; i < data.length; i++) if(data[i] != bytes[i]) throw new RuntimeException("Public key mismatch");*/ try (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) { out.writeBytes(requestValue); out.flush(); } try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { StringBuffer response = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { if (response.length() > 0) response.append('\n'); response.append(line); } if (response.toString().trim().isEmpty()) return null; try { JSONParser parser = new JSONParser(); Object responseObject = parser.parse(response.toString()); if (!(responseObject instanceof JSONObject)) throw new IOException("Response not type of JSONObject: " + response); return (JSONObject) responseObject; } catch (ParseException exception) { throw new IOException("Response not valid JSON: " + response, exception); } } } catch (IOException exception) { throw exception; } catch (Exception exception) { throw new IOException("Error connecting", exception); } finally { if (connection != null) connection.disconnect(); } }
From source file:org.whispersystems.signalservice.internal.push.PushServiceSocket.java
private void uploadAttachment(String method, String url, InputStream data, long dataSize, byte[] key, ProgressListener listener) throws IOException { URL uploadUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) uploadUrl.openConnection(); connection.setDoOutput(true);// w ww. j av a 2s . c om if (dataSize > 0) { connection .setFixedLengthStreamingMode((int) AttachmentCipherOutputStream.getCiphertextLength(dataSize)); } else { connection.setChunkedStreamingMode(0); } connection.setRequestMethod(method); connection.setRequestProperty("Content-Type", "application/octet-stream"); connection.setRequestProperty("Connection", "close"); connection.connect(); try { OutputStream stream = connection.getOutputStream(); AttachmentCipherOutputStream out = new AttachmentCipherOutputStream(key, stream); byte[] buffer = new byte[4096]; int read, written = 0; while ((read = data.read(buffer)) != -1) { out.write(buffer, 0, read); written += read; if (listener != null) { listener.onAttachmentProgress(dataSize, written); } } data.close(); out.flush(); out.close(); if (connection.getResponseCode() != 200) { throw new IOException( "Bad response: " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } finally { connection.disconnect(); } }
From source file:org.disrupted.rumble.database.statistics.StatisticManager.java
public void onEventAsync(LinkLayerStarted event) { if (!event.linkLayerIdentifier.equals(WifiLinkLayerAdapter.LinkLayerIdentifier)) return;//www.j a va2 s . c om if (RumblePreferences.UserOkWithSharingAnonymousData(RumbleApplication.getContext()) && RumblePreferences.isTimeToSync(RumbleApplication.getContext())) { if (!NetUtil.isURLReachable("http://disruptedsystems.org/")) return; try { // generate the JSON file byte[] json = generateStatJSON().toString().getBytes(); // configure SSL CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = new BufferedInputStream( RumbleApplication.getContext().getAssets().open("certs/disruptedsystemsCA.pem")); Certificate ca = cf.generateCertificate(caInput); String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); URL url = new URL("https://data.disruptedsystems.org/post"); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(sslContext.getSocketFactory()); // then configure the header urlConnection.setInstanceFollowRedirects(true); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestProperty("charset", "utf-8"); urlConnection.setRequestProperty("Content-Length", Integer.toString(json.length)); urlConnection.setUseCaches(false); // connect and send the JSON urlConnection.setConnectTimeout(10 * 1000); urlConnection.connect(); urlConnection.getOutputStream().write(json); if (urlConnection.getResponseCode() != 200) throw new IOException("request failed"); // erase the database RumblePreferences.updateLastSync(RumbleApplication.getContext()); cleanDatabase(); } catch (Exception ex) { Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString()); } } }