List of usage examples for javax.net.ssl HttpsURLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:com.github.dfa.diaspora_android.service.FetchPodsService.java
private void getPods() { AsyncTask<Void, Void, DiasporaPodList> getPodsAsync = new AsyncTask<Void, Void, DiasporaPodList>() { @Override/* w ww . java2 s . c o m*/ protected DiasporaPodList doInBackground(Void... params) { StringBuilder sb = new StringBuilder(); BufferedReader br = null; try { HttpsURLConnection con = NetCipher.getHttpsURLConnection(PODDY_PODLIST_URL); if (con.getResponseCode() == HttpsURLConnection.HTTP_OK) { br = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; while ((line = br.readLine()) != null) { sb.append(line); } // Parse JSON & return pod list JSONObject json = new JSONObject(sb.toString()); return new DiasporaPodList().fromJson(json); } else { AppLog.e(this, "Failed to download list of pods"); } } catch (IOException | JSONException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException ignored) { } } } // Could not fetch list of pods :( return new DiasporaPodList(); } @Override protected void onPostExecute(DiasporaPodList pods) { if (pods == null) { pods = new DiasporaPodList(); } Intent broadcastIntent = new Intent(MESSAGE_PODS_RECEIVED); broadcastIntent.putExtra(EXTRA_PODLIST, pods); LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcastIntent); stopSelf(); } }; getPodsAsync.execute(); }
From source file:xyz.karpador.godfishbot.commands.GofCommand.java
@Override public CommandResult getReply(String params, Message message, String myName) { if (params == null) return new CommandResult(getUsage() + "\n" + getDescription()); CommandResult result = new CommandResult(); try {/*from w w w . ja v a 2 s . com*/ String urlString = "https://gifbase.com/tag/" + params + "?format=json"; URL url = new URL(urlString); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setConnectTimeout(4000); if (con.getResponseCode() == HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder httpResult = new StringBuilder(); String line; while ((line = br.readLine()) != null) httpResult.append(line); JSONObject resultJson = new JSONObject(httpResult.toString()); int pageCount = resultJson.optInt("page_count", 1); if (pageCount > 1) { int page = Main.Random.nextInt(pageCount - 1) + 1; if (page != resultJson.getInt("page_current")) { urlString += "&p=" + page; url = new URL(urlString); con = (HttpsURLConnection) url.openConnection(); con.setConnectTimeout(4000); if (con.getResponseCode() == HTTP_OK) { br = new BufferedReader(new InputStreamReader(con.getInputStream())); httpResult.setLength(0); while ((line = br.readLine()) != null) httpResult.append(line); resultJson = new JSONObject(httpResult.toString()); } } } JSONArray gifs = resultJson.optJSONArray("gifs"); if (gifs != null) { JSONObject gif = gifs.getJSONObject(Main.Random.nextInt(gifs.length())); result.imageUrl = gif.getString("url"); } else return null; } else { return new CommandResult("gifbase.com responded with error code: " + con.getResponseCode() + ": " + con.getResponseMessage()); } } catch (IOException | JSONException e) { e.printStackTrace(); return null; } if (result.imageUrl == null) return null; result.isGIF = true; return result; }
From source file:xyz.karpador.godfishbot.commands.WaCommand.java
@Override public CommandResult getReply(String params, Message message, String myName) { CommandResult result = new CommandResult(); if (params != null) { // Get a wallpaper by search term try {/*from ww w . ja v a 2 s . c o m*/ URL url = new URL("https://wall.alphacoders.com/api2.0/get.php" + "?auth=" + BotConfig.getInstance().getAlphacodersToken() + "&method=search&term=" + URLEncoder.encode(params, "UTF-8")); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); if (con.getResponseCode() == HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String httpResult = br.readLine(); JSONObject resultJson = new JSONObject(httpResult); int totalHits = resultJson.getInt("total_match"); if (totalHits < 1) { result.replyToId = message.getMessageId(); result.text = "No results found."; return result; } int pageNumber = 1; if (totalHits > 30) pageNumber = Main.Random.nextInt((int) Math.ceil(totalHits / 30)) + 1; if (pageNumber > 1) { url = new URL(url.toString() + "&page=" + pageNumber); con = (HttpsURLConnection) url.openConnection(); if (con.getResponseCode() == HTTP_OK) { br = new BufferedReader(new InputStreamReader(con.getInputStream())); httpResult = br.readLine(); resultJson = new JSONObject(httpResult); } } if (resultJson.getBoolean("success")) { JSONArray imgs = resultJson.getJSONArray("wallpapers"); JSONObject img = imgs.getJSONObject(Main.Random.nextInt(imgs.length())); result.imageUrl = img.getString("url_thumb"); result.text = img.getString("url_page"); } else { result.text = resultJson.getString("error"); } } } catch (Exception e) { e.printStackTrace(); return null; } } else { // Get a random wallpaper try { URL url = new URL("https://wall.alphacoders.com/api2.0/get.php" + "?auth=" + BotConfig.getInstance().getAlphacodersToken() + "&method=random&count=1"); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); if (con.getResponseCode() == HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String httpResult = br.readLine(); JSONObject resultJson = new JSONObject(httpResult); if (resultJson.getBoolean("success")) { JSONObject img = resultJson.getJSONArray("wallpapers").getJSONObject(0); result.imageUrl = img.getString("url_thumb"); result.text = img.getString("url_page"); } else { result.text = resultJson.getString("error"); } } } catch (Exception e) { e.printStackTrace(); return null; } } return result; }
From source file:com.hybris.mobile.data.WebServiceDataProvider.java
/** * Synchronous call to get a new client credentials token, required for creating new account * /*from ww w . jav a 2 s . co m*/ * @param url * @param clientCredentialsToken * @param httpMethod * @param httpBody * @return The data from the server as a string, in almost all cases JSON * @throws MalformedURLException * @throws IOException * @throws ProtocolException * @throws JSONException */ public static String getClientCredentialsResponse(Context context, String url, String clientCredentialsToken, String httpMethod, Bundle httpBody) throws MalformedURLException, IOException, ProtocolException, JSONException { boolean refreshLimitReached = false; int refreshed = 0; String response = ""; while (!refreshLimitReached) { // If we have refreshed max number of times, we will not do so again if (refreshed == 1) { refreshLimitReached = true; } HttpsURLConnection connection = createSecureConnection(new URL(addParameters(context, url))); trustAllHosts(); connection.setHostnameVerifier(DO_NOT_VERIFY); connection.setRequestMethod(httpMethod); connection.setDoOutput(true); connection.setDoInput(true); String authValue = "Bearer " + clientCredentialsToken; connection.setRequestProperty("Authorization", authValue); connection.connect(); if (!httpBody.isEmpty()) { OutputStream os = new BufferedOutputStream(connection.getOutputStream()); os.write(encodePostBody(httpBody).getBytes()); os.flush(); } try { LoggingUtils.d(LOG_TAG, connection.toString()); response = readFromStream(connection.getInputStream()); } catch (FileNotFoundException e) { response = readFromStream(connection.getErrorStream()); } finally { connection.disconnect(); } // Allow for calls to return nothing if (response.length() == 0) { return ""; } // Check for JSON parsing errors (will throw JSONException is can't be parsed) JSONObject object = new JSONObject(response); // If no error, return response if (!object.has("error")) { return response; } // If there is a refresh token error, refresh the token else if (object.getString("error").equals("invalid_token")) { if (refreshLimitReached) { // Give up return response; } else { // Refresh the token WebServiceAuthProvider.refreshAccessToken(context); refreshed++; } } } // while(!refreshLimitReached) return response; }
From source file:com.example.onenoteservicecreatepageexample.SendRefreshTokenAsyncTask.java
private Object[] parseRefreshTokenResponse(HttpsURLConnection refreshTokenConnection) throws IOException, JSONException { BufferedReader refreshTokenResponseReader = null; try {/*from w ww. j a v a 2 s . c o m*/ refreshTokenResponseReader = new BufferedReader( new InputStreamReader(refreshTokenConnection.getInputStream())); String temporary = null; StringBuffer response = new StringBuffer(); while ((temporary = refreshTokenResponseReader.readLine()) != null) { response.append(temporary); response.append("\n"); } JSONObject refreshTokenResponse = new JSONObject(response.toString()); Object[] refreshTokenResult = new Object[3]; refreshTokenResult[0] = (String) refreshTokenResponse.get("access_token"); refreshTokenResult[1] = (String) refreshTokenResponse.get("refresh_token"); refreshTokenResult[2] = (Integer) refreshTokenResponse.get("expires_in"); return refreshTokenResult; } finally { if (refreshTokenResponseReader != null) { refreshTokenResponseReader.close(); } } }
From source file:ConnectionProtccol.HttpsClient.java
private String ConnectionHandler(HttpsURLConnection con) { BufferedReader br = null;/*from w w w. j ava 2 s. c om*/ if (con != null) { try { br = new BufferedReader(new InputStreamReader(con.getInputStream())); String input; String result = ""; while ((input = br.readLine()) != null) { result += input; } br.close(); // loggerObj.log(Level.INFO, "Result recieved from connection is "+ result); return result; } catch (IOException e) { if (br != null) { try { br.close(); } catch (IOException ex) { loggerObj.log(Level.SEVERE, "Exception while closing Connection " + e); } } loggerObj.log(Level.SEVERE, "Exception while trying to establish connection with MEDC portal" + e.toString()); System.out .println("Exception while trying to establish connection with MEDC portal" + e.toString()); return null; } } return null; }
From source file:xyz.karpador.godfishbot.commands.RikkaCommand.java
@Override public CommandResult getReply(String params, Message message, String myName) { if (imgUrls == null) { if (fileHelper.fileExists()) { String fileContent = fileHelper.getReadData(); if (fileContent != null) { try { JSONObject fileJson = new JSONObject(fileContent); JSONArray urlsData = fileJson.getJSONArray("urls"); imgUrls = new ArrayList<>(); for (int i = 0; i < urlsData.length(); i++) { JSONArray values = urlsData.getJSONArray(i); imgUrls.add(new String[] { values.getString(0), values.getString(1), values.optString(2, null) }); }//from w w w . j av a 2 s . c o m } catch (JSONException e) { e.printStackTrace(); imgUrls = null; } } } if (imgUrls == null) { imgUrls = new ArrayList<>(); try { for (int j = 1; j < 4; j++) { URL url = new URL("https://wall.alphacoders.com/api2.0/get.php" + "?auth=" + BotConfig.getInstance().getAlphacodersToken() + "&method=tag&id=35982&page=" + j); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); if (con.getResponseCode() == HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String result = br.readLine(); JSONObject resultJson = new JSONObject(result); if (resultJson.getBoolean("success")) { JSONArray imgs = resultJson.getJSONArray("wallpapers"); for (int i = 0; i < imgs.length(); i++) { JSONObject currentImg = imgs.getJSONObject(i); imgUrls.add(new String[] { currentImg.getString("url_thumb"), currentImg.getString("url_image"), null }); } writeCurrentState(); } } } } catch (IOException | JSONException e) { e.printStackTrace(); return null; } } } CommandResult result = new CommandResult(); String[] image = imgUrls.get(Main.Random.nextInt(imgUrls.size())); result.imageUrl = image[0]; result.text = image[1]; result.mediaId = image[2]; return result; }
From source file:com.jrummyapps.android.safetynet.SafetyNetHelper.java
/** * Validate the SafetyNet response using the Android Device Verification API. This API performs a validation check on * the JWS message returned from the SafetyNet service. * * <b>Important:</b> This use of the Android Device Verification API only validates that the provided JWS message was * received from the SafetyNet service. It <i>does not</i> verify that the payload data matches your original * compatibility check request./*from w w w . j a v a 2 s . c o m*/ * * @param jws * The output of {@link SafetyNetApi.AttestationResult#getJwsResult()}. * @param apiKey * The Android Device Verification API key * @return {@code true} if the provided JWS message was received from the SafetyNet service. * @throws SafetyNetError * if an error occurs while verifying the JSON Web Signature. */ public static boolean validate(@NonNull String jws, @NonNull String apiKey) throws SafetyNetError { try { URL verifyApiUrl = new URL(GOOGLE_VERIFICATION_URL + apiKey); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); TrustManager[] defaultTrustManagers = trustManagerFactory.getTrustManagers(); TrustManager[] trustManagers = Arrays.copyOf(defaultTrustManagers, defaultTrustManagers.length + 1); trustManagers[defaultTrustManagers.length] = new GoogleApisTrustManager(); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagers, null); HttpsURLConnection urlConnection = (HttpsURLConnection) verifyApiUrl.openConnection(); urlConnection.setSSLSocketFactory(sslContext.getSocketFactory()); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-Type", "application/json"); JSONObject requestJson = new JSONObject(); requestJson.put("signedAttestation", jws); byte[] outputInBytes = requestJson.toString().getBytes("UTF-8"); OutputStream os = urlConnection.getOutputStream(); os.write(outputInBytes); os.close(); urlConnection.connect(); InputStream is = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); for (String line = reader.readLine(), nl = ""; line != null; line = reader.readLine(), nl = "\n") { sb.append(nl).append(line); } return new JSONObject(sb.toString()).getBoolean("isValidSignature"); } catch (Exception e) { throw new SafetyNetError(e); } }
From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java
public static HttpsResponse deleteWithBasicAuth(String uri, String contentType, String userName, String password) throws IOException { if (uri.startsWith("https://")) { URL url = new URL(uri); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("DELETE"); String encode = new String( new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes())) .replaceAll("\n", ""); ;// w w w . jav a 2 s. c o m conn.setRequestProperty("Authorization", "Basic " + encode); if (contentType != null) { conn.setRequestProperty("Content-Type", contentType); } conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); conn.connect(); StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } finally { if (rd != null) { rd.close(); } conn.disconnect(); } return new HttpsResponse(sb.toString(), conn.getResponseCode()); } return null; }
From source file:xyz.karpador.godfishbot.commands.FlauschCommand.java
@Override public CommandResult getReply(String params, Message message, String myName) { if (imgUrls == null) { String fileContent = fileHelper.getReadData(); if (fileContent != null) { try { JSONObject fileJson = new JSONObject(fileContent); JSONArray urlsData = fileJson.getJSONArray("urls"); imgUrls = new ArrayList<>(); for (int i = 0; i < urlsData.length(); i++) { JSONArray values = urlsData.getJSONArray(i); imgUrls.add(new String[] { values.getString(0), values.optString(1, null) }); }//from w w w .ja va 2 s. c om lastRefreshDate = new Date(fileJson.getLong("refresh_date")); } catch (JSONException e) { e.printStackTrace(); } } } if (imgUrls == null || new Date().getTime() >= lastRefreshDate.getTime() + (24 * 3600 * 1000)) { imgUrls = new ArrayList<>(); // Populate the list with pixabay URLs try { for (int j = 1; j < 10; j++) { URL url = new URL("https://pixabay.com/api/" + "?key=" + BotConfig.getInstance().getPixabayToken() + "&q=bunny" + "&image_type=photo&category=animals&pretty=false" + "&page=" + j); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); if (con.getResponseCode() == HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder result = new StringBuilder(); String line; while ((line = br.readLine()) != null) result.append(line); JSONObject resultJson = new JSONObject(result.toString()); JSONArray hits = resultJson.getJSONArray("hits"); for (int i = 0; i < hits.length(); i++) { JSONObject currentImg = hits.getJSONObject(i); String tags = currentImg.getString("tags"); if (stringContainsAny(tags, BLOCKTAGS)) continue; imgUrls.add(new String[] { currentImg.getString("webformatURL"), null }); } lastRefreshDate = new Date(); writeCurrentState(); } } } catch (IOException | JSONException e) { e.printStackTrace(); return null; } } CommandResult result = new CommandResult(); String[] data = imgUrls.get(Main.Random.nextInt(imgUrls.size())); result.imageUrl = data[0]; result.mediaId = data[1]; return result; }