List of usage examples for javax.net.ssl HttpsURLConnection connect
public abstract void connect() throws IOException;
From source file:org.sufficientlysecure.keychain.ui.linked.LinkedIdCreateGithubFragment.java
private static JSONObject jsonHttpRequest(String url, JSONObject params, String accessToken) throws IOException, HttpResultException { HttpsURLConnection nection = (HttpsURLConnection) new URL(url).openConnection(); nection.setDoInput(true);//from w w w .ja va2 s . c om nection.setDoOutput(true); nection.setConnectTimeout(2000); nection.setReadTimeout(1000); nection.setRequestProperty("Content-Type", "application/json"); nection.setRequestProperty("Accept", "application/json"); nection.setRequestProperty("User-Agent", "OpenKeychain " + BuildConfig.VERSION_NAME); if (accessToken != null) { nection.setRequestProperty("Authorization", "token " + accessToken); } OutputStream os = nection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(params.toString()); writer.flush(); writer.close(); os.close(); try { nection.connect(); int code = nection.getResponseCode(); if (code != HttpsURLConnection.HTTP_CREATED && code != HttpsURLConnection.HTTP_OK) { throw new HttpResultException(nection.getResponseCode(), nection.getResponseMessage()); } InputStream in = new BufferedInputStream(nection.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); while (true) { String line = reader.readLine(); if (line == null) { break; } response.append(line); } try { return new JSONObject(response.toString()); } catch (JSONException e) { throw new IOException(e); } } finally { nection.disconnect(); } }
From source file:com.microsoft.onenote.pickerlib.ApiRequestAsyncTask.java
private JSONObject getJSONResponse(String endpoint) throws Exception { HttpsURLConnection mUrlConnection = (HttpsURLConnection) (new URL(endpoint)).openConnection(); mUrlConnection.setRequestProperty("User-Agent", System.getProperty("http.agent") + " Android OneNotePicker"); if (mAccessToken != null) { mUrlConnection.setRequestProperty("Authorization", "Bearer " + mAccessToken); }/*from w ww . j a v a2 s .c o m*/ mUrlConnection.connect(); int responseCode = mUrlConnection.getResponseCode(); String responseMessage = mUrlConnection.getResponseMessage(); String responseBody = null; boolean responseIsJson = mUrlConnection.getContentType().contains("application/json"); JSONObject responseObject; if (responseCode == HttpsURLConnection.HTTP_UNAUTHORIZED) { mUrlConnection.disconnect(); throw new ApiException(Integer.toString(responseCode) + " " + responseMessage, null, "Invalid or missing access token.", null); } if (responseIsJson) { InputStream is = null; try { if (responseCode == HttpsURLConnection.HTTP_INTERNAL_ERROR) { is = mUrlConnection.getErrorStream(); } else { is = mUrlConnection.getInputStream(); } BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = null; String lineSeparator = System.getProperty("line.separator"); StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { buffer.append(line); buffer.append(lineSeparator); } responseBody = buffer.toString(); } finally { if (is != null) { is.close(); } mUrlConnection.disconnect(); } responseObject = new JSONObject(responseBody); } else { throw new ApiException(Integer.toString(responseCode) + " " + responseMessage, null, "Unrecognized server response", null); } return responseObject; }
From source file:com.vmware.o11n.plugin.crypto.service.CryptoCertificateService.java
/** * Returns the certificate chain provided by the HTTPS server. * * The first certificate identifies the server. * The remainder should verify the cert upto a trusted root. * * * @param url/*from w ww. j a va2s.c o m*/ * @return * @throws IOException * @throws KeyManagementException * @throws NoSuchAlgorithmException */ public List<X509Certificate> getCertHttps(URL url) throws IOException, KeyManagementException, NoSuchAlgorithmException { ArrayList<X509Certificate> toReturn = new ArrayList<>(); // Setup a temp ssl context that accepts all certificates for this connection SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { new X509TrustManager() { private X509Certificate[] certToReturn; @Override public void checkClientTrusted(X509Certificate[] c, String s) { } @Override public void checkServerTrusted(X509Certificate[] c, String s) { certToReturn = c; } @Override public X509Certificate[] getAcceptedIssuers() { return certToReturn; } } }, null); //Setup a temp hostname verifier that verifies all hostnames for this connection HostnameVerifier hv = new HostnameVerifier() { @Override public boolean verify(String s, SSLSession ss) { return true; } }; HttpsURLConnection httpsConn = null; try { httpsConn = (HttpsURLConnection) url.openConnection(); httpsConn.setSSLSocketFactory(sslContext.getSocketFactory()); httpsConn.setHostnameVerifier(hv); httpsConn.connect(); Certificate[] certs = httpsConn.getServerCertificates(); for (Certificate cert : certs) { if (cert instanceof X509Certificate) { toReturn.add((X509Certificate) cert); } } } finally { if (httpsConn != null) { httpsConn.disconnect(); } } return toReturn; }
From source file:com.illusionaryone.GameWispAPI.java
@SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String methodType, String urlAddress) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; OutputStream outputStream = null; URL urlRaw;/* w w w .j ava 2 s .c o m*/ HttpsURLConnection urlConn; String jsonText = ""; if (sAccessToken.length() == 0) { if (!noAccessWarning) { com.gmt2001.Console.err.println( "GameWispAPI: Attempting to use GameWisp API without key. Disable GameWisp module."); noAccessWarning = true; } JSONStringer jsonObject = new JSONStringer(); return (new JSONObject(jsonObject.object().key("result").object().key("status").value(-1).endObject() .endObject().toString())); } try { urlRaw = new URL(urlAddress); urlConn = (HttpsURLConnection) urlRaw.openConnection(); urlConn.setDoInput(true); urlConn.setRequestMethod(methodType); 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 QuorraBot/2015"); if (methodType.equals("POST")) { urlConn.setDoOutput(true); urlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } else { urlConn.addRequestProperty("Content-Type", "application/json"); } 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, methodType, urlAddress, urlConn.getResponseCode(), "", "", jsonText); } catch (JSONException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "JSONException", ex.getMessage(), jsonText); com.gmt2001.Console.err .println("GameWispAPI::Bad JSON (" + urlAddress + "): " + jsonText.substring(0, 100) + "..."); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (IOException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (Exception ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPI::readJsonFromUrl::Exception: " + ex.getMessage()); } } } return (jsonResult); }
From source file:com.fastbootmobile.twofactorauthdemo.MainActivity.java
protected void registerWithBackend() { final SharedPreferences pref = this.getSharedPreferences(OwnPushClient.PREF_PUSH, Context.MODE_PRIVATE); Thread httpThread = new Thread(new Runnable() { private String TAG = "httpThread"; private String ENDPOINT = "https://otp.demo.ownpush.com/push/register"; @Override/*w w w . j av a 2 s .c o m*/ public void run() { URL urlObj; try { urlObj = new URL(ENDPOINT); String install_id = pref.getString(OwnPushClient.PREF_PUBLIC_KEY, null); if (install_id == null) { return; } String mPostData = "push_id=" + install_id; HttpsURLConnection con = (HttpsURLConnection) urlObj.openConnection(); con.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) "); con.setRequestProperty("Accept", "*/*"); con.setDoInput(true); con.setRequestMethod("POST"); con.getOutputStream().write(mPostData.getBytes()); con.connect(); int http_status = con.getResponseCode(); if (http_status != 200) { Log.e(TAG, "ERROR IN HTTP REPONSE : " + http_status); return; } InputStream stream; stream = con.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(stream)); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); String data = sb.toString(); if (data.contains("device_uid")) { JSONObject json = new JSONObject(data); String device_id = json.getString("device_uid"); pref.edit().putString("device_uid", device_id).commit(); Log.d(TAG, "GOT DEVICE UID OF " + device_id); mHandler.post(new Runnable() { @Override public void run() { updateUI(); } }); } } catch (Exception e) { e.printStackTrace(); } } }); httpThread.start(); }
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 ww w .j ava 2s .c om*/ 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:in.rab.ordboken.NeClient.java
private String fetchMainSitePage(String pageUrl) throws IOException, LoginException, ParserException { URL url = new URL(pageUrl); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setInstanceFollowRedirects(false); urlConnection.connect(); int response; try {/* ww w . j a v a 2 s .c o m*/ response = urlConnection.getResponseCode(); } catch (IOException e) { urlConnection.disconnect(); throw e; } if (response == 302) { urlConnection.disconnect(); try { loginMainSite(); } catch (EOFException e) { // Same EOFException as on token refreshes. Seems to be a POST thing. loginMainSite(); } url = new URL(pageUrl); urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setInstanceFollowRedirects(false); urlConnection.connect(); try { response = urlConnection.getResponseCode(); } catch (IOException e) { urlConnection.disconnect(); throw e; } } try { if (response != 200) { throw new ParserException("Unable to get page: " + response); } return inputStreamToString(urlConnection.getInputStream()); } finally { urlConnection.disconnect(); } }
From source file:org.wso2.carbon.integration.common.tests.JaggeryServerTest.java
/** * Sending the request and getting the response * @param Uri - request url//from ww w. j ava 2 s . c o m * @param append - append request parameters * @throws IOException */ private HttpsResponse getRequest(String Uri, String requestParameters, boolean append) throws IOException { if (Uri.startsWith("https://")) { String urlStr = Uri; if (requestParameters != null && requestParameters.length() > 0) { if (append) { urlStr += "?" + requestParameters; } else { urlStr += requestParameters; } } URL url = new URL(urlStr); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); conn.setReadTimeout(30000); conn.connect(); // Get the response StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } catch (IOException ignored) { } finally { if (rd != null) { rd.close(); } conn.disconnect(); } return new HttpsResponse(sb.toString(), conn.getResponseCode()); } return null; }
From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java
@Override public int checkConnection(String testRequest) { try {/*from w w w . j a v a2s . c o m*/ HttpsURLConnection connection = getConnection(testRequest, connectTimeout, readTimeout); if (connection != null) { connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { if (IOUtils.toString(connection.getInputStream()).contains("Authentication failed")) { return ConnectionManager.AUTHENTIFICATION_PROBLEM; } } connection.disconnect(); return connection.getResponseCode(); } else { return ConnectionManager.GENERAL_EXCEPTION; } } catch (SocketTimeoutException e) { return ConnectionManager.SOCKET_TIMEOUT_EXCEPTION; } catch (java.net.ConnectException e) { return ConnectionManager.CONNECTION_EXCEPTION; } catch (MalformedURLException e) { return ConnectionManager.MALFORMED_URL_EXCEPTION; } catch (java.net.UnknownHostException e) { return ConnectionManager.UNKNOWN_HOST_EXCEPTION; } catch (IOException e) { return ConnectionManager.GENERAL_EXCEPTION; } }
From source file:com.illusionaryone.GameWispAPIv1.java
@SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String methodType, String urlAddress) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; OutputStream outputStream = null; URL urlRaw;//from ww w . ja v a 2 s . c om HttpsURLConnection urlConn; String jsonText = ""; if (sAccessToken.length() == 0) { if (!noAccessWarning) { com.gmt2001.Console.err.println( "GameWispAPIv1: Attempting to use GameWisp API without key. Disabling the GameWisp module."); PhantomBot.instance().getDataStore().set("modules", "./handlers/gameWispHandler.js", "false"); noAccessWarning = true; } JSONStringer jsonObject = new JSONStringer(); return (new JSONObject(jsonObject.object().key("result").object().key("status").value(-1).endObject() .endObject().toString())); } try { urlRaw = new URL(urlAddress); urlConn = (HttpsURLConnection) urlRaw.openConnection(); urlConn.setDoInput(true); urlConn.setRequestMethod(methodType); 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"); if (methodType.equals("POST")) { urlConn.setDoOutput(true); urlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } else { urlConn.addRequestProperty("Content-Type", "application/json"); } 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, methodType, urlAddress, urlConn.getResponseCode(), "", "", jsonText); } catch (JSONException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "JSONException", ex.getMessage(), jsonText); com.gmt2001.Console.err .println("GameWispAPIv1::Bad JSON (" + urlAddress + "): " + jsonText.substring(0, 100) + "..."); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (IOException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } catch (Exception ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.err.println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException ex) { fillJSONObject(jsonResult, false, methodType, urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err .println("GameWispAPIv1::readJsonFromUrl::Exception: " + ex.getMessage()); } } return (jsonResult); }