List of usage examples for javax.net.ssl HttpsURLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:org.maikelwever.droidpile.backend.ApiConnecter.java
public String getData(boolean cache, String... data) throws IOException, JSONException { if (data.length < 1) { throw new IllegalArgumentException("More than 1 argument is required."); }// w ww . jav a2 s . c om boolean foundOne = false; for (String endpoint : this.allowed_endpoints) { if (endpoint.equals(data[0])) { foundOne = true; break; } } if (!foundOne) { throw new IllegalArgumentException("Endpoint name is not in 'allowed_endpoints'."); } String url = this.baseUrl; String suffix = ""; for (String arg : data) { suffix += "/" + arg; } Log.d("droidpile", "URL we will call: " + url + suffix); String json = null; if (this.useCache) { json = this.getCachedRecordForQuery(suffix); } if (json == null || json.isEmpty()) { url += suffix; URL uri = new URL(url); InputStreamReader is; if (url.startsWith("https")) { HttpsURLConnection con = (HttpsURLConnection) uri.openConnection(); if (!this.basicAuth.isEmpty()) { con.setRequestProperty("Authorization", basicAuth); } is = new InputStreamReader(con.getInputStream(), ENCODING); } else { HttpURLConnection con = (HttpURLConnection) uri.openConnection(); if (!this.basicAuth.isEmpty()) { con.setRequestProperty("Authorization", basicAuth); } is = new InputStreamReader(con.getInputStream(), ENCODING); } StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(is); String read = br.readLine(); while (read != null) { sb.append(read); read = br.readLine(); } String stringData = sb.toString(); if (this.useCache) { this.storeInCache(suffix, stringData); } return stringData; } else { return json; } }
From source file:com.persistent.cloudninja.scheduler.DeploymentMonitor.java
/** * Gets the information regarding the roles and their instances * of the deployment. It makes a call to REST API and gets the XML response. * /*from w w w. j a va 2s.c om*/ * @return XML response * @throws IOException */ public StringBuffer getRoleInfoForDeployment() throws IOException { StringBuffer response = new StringBuffer(); System.setProperty("javax.net.ssl.keyStoreType", "pkcs12"); StringBuffer keyStore = new StringBuffer(); keyStore.append(System.getProperty("java.home")); LOGGER.debug("java.home : " + keyStore.toString()); if (keyStore.length() == 0) { keyStore.append(System.getenv("JRE_HOME")); LOGGER.debug("JRE_HOME : " + keyStore.toString()); } keyStore.append(File.separator + "lib\\security\\CloudNinja.pfx"); System.setProperty("javax.net.ssl.keyStore", keyStore.toString()); System.setProperty("javax.net.debug", "ssl"); System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword); System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); // form the URL which will return the response // containing info of roles and their instances. StringBuffer strURL = new StringBuffer(host); strURL.append(subscriptionId); strURL.append("/services/hostedservices/"); strURL.append(hostedServiceName); strURL.append("/deploymentslots/"); strURL.append(deploymentType); URL url = new URL(strURL.toString()); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setSSLSocketFactory(sslSocketFactory); connection.setRequestMethod("GET"); connection.setAllowUserInteraction(false); // set the x-ms-version in header which is a compulsory parameter to get response connection.setRequestProperty("x-ms-version", "2011-10-01"); connection.setRequestProperty("Content-type", "text/xml"); connection.setRequestProperty("accept", "text/xml"); // get the response as input stream InputStream inputStream = connection.getInputStream(); InputStreamReader streamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(streamReader); String string = null; while ((string = bufferedReader.readLine()) != null) { response.append(string); } return response; }
From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java
private static String makePostApiCall(URL url, String content, String authToken) throws IOException { HttpsURLConnection conn = null; OutputStreamWriter writer = null; String res = ""; try {//from w ww . j a v a 2 s.c om conn = (HttpsURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Authorization", "Bearer " + authToken); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(content); writer.close(); if (conn.getResponseCode() / 100 >= 3) { Log.v("makePostApiCall", "Post content is: " + content); String error = ""; try { JsonReader r = new JsonReader(new InputStreamReader(conn.getErrorStream(), "UTF-8")); r.beginObject(); while (r.hasNext()) { error += r.nextName() + ": " + r.nextString() + "\r\n"; } r.endObject(); r.close(); } catch (Throwable eex) { } Log.v("makePostApiCall", "Error string is: " + error); res = error; throw new IOException( "Response code: " + conn.getResponseCode() + " URL is: " + url + " \nError: " + error); } else { JsonReader r = new JsonReader(new InputStreamReader(conn.getInputStream())); r.beginObject(); while (r.hasNext()) { try { res += r.nextName() + ": " + r.nextString() + "\n"; } catch (Exception ex) { r.skipValue(); } } return res; } } finally { conn.disconnect(); //return res; } }
From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java
public static String[] getAccessTokens(final String[] requests) throws Exception { final String TAG = "getAccesTokens"; String code = requests[0];// w ww . j av a 2s . c o m String clientIdAndSecret = QUIZLET_CLIENT_ID + ":" + QUIZLET_CLIENT_SECRET; String encodedClientIdAndSecret = Base64.encodeToString(clientIdAndSecret.getBytes(), 0); URL url1 = new URL("https://api.quizlet.com/oauth/token"); HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection(); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // Add the Basic Authorization item conn.addRequestProperty("Authorization", "Basic " + encodedClientIdAndSecret); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); String payload = String.format("grant_type=%s&code=%s&redirect_uri=%s", URLEncoder.encode("authorization_code", "UTF-8"), URLEncoder.encode(code, "UTF-8"), URLEncoder.encode(Data.RedirectURI, "UTF-8")); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write(payload); out.close(); if (conn.getResponseCode() / 100 >= 3) { Log.e(TAG, "Http response code: " + conn.getResponseCode() + " response message: " + conn.getResponseMessage()); JsonReader r = new JsonReader(new InputStreamReader(conn.getErrorStream(), "UTF-8")); String error = ""; r.beginObject(); while (r.hasNext()) { error += r.nextName() + r.nextString() + "\r\n"; } r.endObject(); r.close(); Log.e(TAG, "Error response for: " + url1 + " is " + error); throw new IOException("Response code: " + conn.getResponseCode()); } JsonReader s = new JsonReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); try { String accessToken = null; String userId = null; s.beginObject(); while (s.hasNext()) { String name = s.nextName(); if (name.equals("access_token")) { accessToken = s.nextString(); } else if (name.equals("user_id")) { userId = s.nextString(); } else { s.skipValue(); } } s.endObject(); s.close(); return new String[] { accessToken, userId }; } catch (Exception e) { // Throw out JSON exception. it is unlikely to happen throw new RuntimeException(e); } finally { conn.disconnect(); } }
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;/* w w w.ja va 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); }
From source file:hudson.plugins.boundary.Boundary.java
public void sendEvent(AbstractBuild<?, ?> build, BuildListener listener) throws IOException { final HashMap<String, Object> event = new HashMap<String, Object>(); event.put("fingerprintFields", Arrays.asList("build name")); final Map<String, String> source = new HashMap<String, String>(); String hostname = "localhost"; try {/* w ww. j a v a 2s . c o m*/ hostname = java.net.InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { listener.getLogger().println("host lookup exception: " + e); } source.put("ref", hostname); source.put("type", "jenkins"); event.put("source", source); final Map<String, String> properties = new HashMap<String, String>(); properties.put("build status", build.getResult().toString()); properties.put("build number", build.getDisplayName()); properties.put("build name", build.getProject().getName()); event.put("properties", properties); event.put("title", String.format("Jenkins Build Job - %s - %s", build.getProject().getName(), build.getDisplayName())); if (Result.SUCCESS.equals(build.getResult())) { event.put("severity", "INFO"); event.put("status", "CLOSED"); } else { event.put("severity", "WARN"); event.put("status", "OPEN"); } final String url = String.format("https://api.boundary.com/%s/events", this.id); final HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); final String authHeader = "Basic " + new String(Base64.encodeBase64((token + ":").getBytes(), false)); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setDoOutput(true); InputStream is = null; OutputStream os = null; try { os = conn.getOutputStream(); OBJECT_MAPPER.writeValue(os, event); os.flush(); is = conn.getInputStream(); } finally { close(is); close(os); } final int responseCode = conn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_CREATED) { listener.getLogger().println("Invalid HTTP response code from Boundary API: " + responseCode); } else { String location = conn.getHeaderField("Location"); if (location.startsWith("http:")) { location = "https" + location.substring(4); } listener.getLogger().println("Created Boundary Event: " + location); } }
From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java
@Override public int checkConnection(String testRequest) { try {/* w w w . ja v a 2s. co 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:net.mms_projects.copy_it.server.push.android.GCMRunnable.java
public void run() { try {/*from w w w . j a v a2 s. co m*/ URL url = new URL(GCM_URL); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod(POST); conn.setRequestProperty(CONTENT_TYPE, Page.ContentTypes.JSON_TYPE); conn.setRequestProperty(AUTHORIZATION, KEY); final String output_json = full.toString(); System.err.println("Input json: " + output_json); conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(output_json.length())); conn.setDoOutput(true); conn.setDoInput(true); DataOutputStream outputstream = new DataOutputStream(conn.getOutputStream()); outputstream.writeBytes(output_json); outputstream.close(); DataInputStream input = new DataInputStream(conn.getInputStream()); StringBuilder builder = new StringBuilder(input.available()); for (int c = input.read(); c != -1; c = input.read()) builder.append((char) c); input.close(); output = new JSONObject(builder.toString()); System.err.println("Output json: " + output.toString()); } catch (Exception e) { e.printStackTrace(); } }
From source file:kltn.controller.StartController.java
public void getLatLong() throws InterruptedException, MalformedURLException, IOException, ParseException { ATMLocationDAO atmDAO = new ATMLocationDAO(); List<AtmLocation> atmList = atmDAO.findGeocodingList(); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(Integer.toString(atmList.size()))); for (AtmLocation atm : atmList) { // AtmLocation atm = atmList.get(2); StringBuilder sb = new StringBuilder(); if (atm.getStreet() != null) { sb.append(atm.getStreet());/* w ww . j a v a 2s .c o m*/ sb.append(","); } if (atm.getPrecinct() != null) { sb.append(atm.getPrecinct()); sb.append(","); } if (atm.getDistrict() != null) { sb.append(atm.getDistrict()); sb.append(","); } sb.append(atm.getProvinceCity()); sb.append(", Viet Nam"); String link = "https://maps.googleapis.com/maps/api/geocode/json?&key=AIzaSyALCgmmer3Cht-mFQiaJC9yoWdSqvfdAiM"; link = link + "&address=" + URLEncoder.encode(sb.toString(), "UTF-8"); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(link)); status2 = link; URL url = new URL(link); HttpsURLConnection httpsCon = (HttpsURLConnection) url.openConnection(); InputStream is = httpsCon.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, "UTF-8"); String jsonString = writer.toString(); // System.out.println(jsonString); // System.out.println("----------------------------------------"); JSONParser parse = new JSONParser(); Object obj = parse.parse(jsonString); JSONObject jsonObject = (JSONObject) obj; FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(jsonObject.get("status").toString())); if (jsonObject.get("status").toString().toLowerCase().trim().equals("over_query_limit")) { System.out.println("Reach API LIMIT"); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Reach API LIMIT")); break; } else if (jsonObject.get("status").toString().toLowerCase().trim().equals("invalid_request")) { System.out.println("INVALID REQUEST"); System.out.println(link); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(sb.toString())); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("INVALID REQUEST")); break; } else { JSONArray resultArray = (JSONArray) jsonObject.get("results"); // if (resultArray.size() == 1) { int countMatch = 0; for (Object resultO : resultArray) { JSONObject resultObject = (JSONObject) resultO; JSONArray addressArray = (JSONArray) resultObject.get("address_components"); String street_number = null; String route = null; String precinct = null; String district = null; String province = null; for (Object addressObj : addressArray) { JSONObject addressJsonObj = (JSONObject) addressObj; if (addressJsonObj.get("types") != null) { if (addressJsonObj.get("types").toString().contains("street_number")) { street_number = addressJsonObj.get("long_name").toString(); } else if (addressJsonObj.get("types").toString().contains("route")) { route = addressJsonObj.get("long_name").toString(); } else if (addressJsonObj.get("types").toString().contains("sublocality_level_1")) { precinct = addressJsonObj.get("long_name").toString(); } else if (addressJsonObj.get("types").toString() .contains("administrative_area_level_2")) { district = addressJsonObj.get("long_name").toString(); } else if (addressJsonObj.get("types").toString() .contains("administrative_area_level_1")) { province = addressJsonObj.get("long_name").toString(); } } } if (street_number != null && route != null) { if (atm.getFulladdress().toLowerCase().contains(street_number.toLowerCase()) && atm.getFulladdress().toLowerCase().contains(route.toLowerCase())) { // countMatch++; JSONObject geoJsonObj = (JSONObject) resultObject.get("geometry"); JSONObject locationJsonObj = (JSONObject) geoJsonObj.get("location"); atm.setLatd(locationJsonObj.get("lat").toString()); atm.setLongd(locationJsonObj.get("lng").toString()); } } } System.out.println("============================================================================="); if (atm.getLatd() != null && !atm.getLatd().trim().equals("")) { atmDAO.update(atm); Thread.sleep(300); } } } }
From source file:org.openhab.binding.unifi.internal.UnifiBinding.java
private void logout() { URL url = null;// ww w .j av a 2 s. c o m if (cookies.size() == 0) return; try { url = new URL(getControllerUrl("api/logout")); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Cookie", cookies.get(0) + "; " + cookies.get(1)); connection.getInputStream(); } catch (MalformedURLException e) { logger.error("The URL '" + url + "' is malformed: " + e.toString()); } catch (Exception e) { logger.error("Cannot do logout. Exception: " + e.toString()); } }