Example usage for javax.net.ssl HttpsURLConnection getInputStream

List of usage examples for javax.net.ssl HttpsURLConnection getInputStream

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:xyz.karpador.godfishbot.commands.PbCommand.java

@Override
public CommandResult getReply(String params, Message message, String myName) {
    CommandResult result = new CommandResult();
    try {/*from  w ww . ja v a 2s  . com*/
        String urlString = "https://pixabay.com/api/" + "?key=" + BotConfig.getInstance().getPixabayToken()
                + "&pretty=false";
        if (params != null)
            urlString += "&q=" + URLEncoder.encode(params, "UTF-8");
        URL url = new URL(urlString);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        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 totalHits = resultJson.getInt("totalHits");
            if (totalHits < 1) {
                result.replyToId = message.getMessageId();
                result.text = "No results found.";
                return result;
            }
            int pageNumber = 1;
            if (totalHits > 20) // Generate a valid page number.
                pageNumber = Main.Random.nextInt((int) Math.ceil(totalHits / 15)) + 1;
            if (pageNumber > 1) {
                urlString += "&page=" + pageNumber;
                url = new URL(urlString);
                con = (HttpsURLConnection) url.openConnection();
                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 hits = resultJson.getJSONArray("hits");
            int imageIndex = Main.Random.nextInt(hits.length());
            JSONObject img = hits.getJSONObject(imageIndex);
            result.imageUrl = img.getString("webformatURL");
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return result;
}

From source file:net.minder.KnoxWebHdfsJavaClientExamplesTest.java

@Test
public void getHomeDirExample() throws Exception {
    HttpsURLConnection connection;
    InputStream input;//from   w  ww . ja va  2 s.  c om
    JsonNode json;

    connection = createHttpUrlConnection(WEBHDFS_URL + "?op=GETHOMEDIRECTORY");
    input = connection.getInputStream();
    json = MAPPER.readTree(input);
    input.close();
    connection.disconnect();
    assertThat(json.get("Path").asText(), is("/user/" + TEST_USERNAME));

}

From source file:io.siddhi.doc.gen.extensions.githubclient.ContentsResponse.java

ContentsResponse(HttpsURLConnection connection) throws IOException {
    connection.setRequestProperty("Accept", "application/vnd.githubclient.v3." + mediaType());

    status = connection.getResponseCode();
    stream = (status == 200) ? connection.getInputStream() : connection.getErrorStream();

    headers = connection.getHeaderFields();

    contentsBodyReader = null;/* w w w .j av  a  2  s.co m*/
}

From source file:org.openhab.binding.whistle.internal.WhistleBinding.java

protected static String getAuthToken(String username, String password) throws Exception {
    logger.debug("Using username: '{}' / password: '{}'", username, password);

    URL obj = new URL(APIROOT + "tokens.json");
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    // add request headers and parameters
    con.setDoOutput(true);/* www.java  2  s . c  o  m*/
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("User-Agent", "WhistleApp/102 (iPhone; iOS 7.0.4; Scale/2.00)");
    con.setRequestMethod("POST");
    String urlParameters = "{\"password\":\"" + password + "\",\"email\":\"" + username
            + "\",\"app_id\":\"com.whistle.WhistleApp\"}";
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();
    if (con.getResponseCode() != 200) {
        logger.error("Username / password combination didn't work. Failed to get AuthenticationToken");
        return null;
    }
    // Read the buffer
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String response = in.readLine();
    in.close();
    // Parse the data and return the token
    JsonObject jobj = new Gson().fromJson(response, JsonObject.class);
    return jobj.get("token").getAsString();
}

From source file:mediasearch.twitter.TwitterService.java

public String readResponse(HttpsURLConnection connection) {
    try {/*w w  w  . ja  va 2s  .c o  m*/
        StringBuilder str = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            str.append(line).append(System.getProperty("line.separator"));
        }
        return str.toString();
    } catch (IOException e) {
        return new String();
    }
}

From source file:com.illusionaryone.GoogleURLShortenerAPIv1.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String urlAddress, String longURL) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    URL urlRaw;//  ww w.  jav a 2 s . c o m
    HttpsURLConnection urlConn;
    String jsonRequest = "";
    String jsonText = "";

    try {
        jsonRequest = "{ 'longUrl': '" + longURL + "'}";
        byte[] postRequest = jsonRequest.getBytes("UTF-8");

        urlRaw = new URL(urlAddress);
        urlConn = (HttpsURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setRequestMethod("POST");
        urlConn.addRequestProperty("Content-Type", "application/json");
        urlConn.addRequestProperty("Content-Length", String.valueOf(postRequest.length));
        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();
        urlConn.getOutputStream().write(postRequest);

        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
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (UnsupportedEncodingException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "UnsupportedEncodingException", ex.getMessage(),
                jsonText);
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::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("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
            }
    }

    return (jsonResult);
}

From source file:com.microsoft.office365.msgraphsnippetapp.SnippetsUnitTests.java

@BeforeClass
public static void getAccessTokenUsingPasswordGrant()
        throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, JSONException {
    URL url = new URL(TOKEN_ENDPOINT);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

    String urlParameters = String.format(
            "grant_type=%1$s&resource=%2$s&client_id=%3$s&username=%4$s&password=%5$s", GRANT_TYPE,
            URLEncoder.encode(ServiceConstants.AUTHENTICATION_RESOURCE_ID, "UTF-8"), clientId, username,
            password);/*from   w  ww  . j a v  a  2 s  .co m*/

    connection.setRequestMethod(REQUEST_METHOD);
    connection.setRequestProperty("Content-Type", CONTENT_TYPE);
    connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes("UTF-8").length));

    connection.setDoOutput(true);
    DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
    dataOutputStream.writeBytes(urlParameters);
    dataOutputStream.flush();
    dataOutputStream.close();

    connection.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuilder response = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    JsonParser jsonParser = new JsonParser();
    JsonObject grantResponse = (JsonObject) jsonParser.parse(response.toString());
    accessToken = grantResponse.get("access_token").getAsString();

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            request = request.newBuilder().addHeader("Authorization", "Bearer " + accessToken)
                    // This header has been added to identify this sample in the Microsoft Graph service.
                    // If you're using this code for your project please remove the following line.
                    .addHeader("SampleID", "android-java-snippets-rest-sample").build();

            return chain.proceed(request);
        }
    }).addInterceptor(logging).build();

    Retrofit retrofit = new Retrofit.Builder().baseUrl(ServiceConstants.AUTHENTICATION_RESOURCE_ID)
            .client(client).addConverterFactory(GsonConverterFactory.create()).build();

    contactService = retrofit.create(MSGraphContactService.class);
    drivesService = retrofit.create(MSGraphDrivesService.class);
    eventsService = retrofit.create(MSGraphEventsService.class);
    groupsService = retrofit.create(MSGraphGroupsService.class);
    mailService = retrofit.create(MSGraphMailService.class);
    meService = retrofit.create(MSGraphMeService.class);
    userService = retrofit.create(MSGraphUserService.class);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.US);
    dateTime = simpleDateFormat.format(new Date());
}

From source file:org.apache.hadoop.io.crypto.bee.RestClient.java

private InputStream httpsWithCertificate(final URL url) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null);// Make an empty store

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    FileInputStream fis = new FileInputStream(BeeConstants.BEE_HTTPS_CERTIFICATE_DEFAULT_PATH);
    BufferedInputStream bis = new BufferedInputStream(fis);
    while (bis.available() > 0) {
        Certificate cert = cf.generateCertificate(bis);
        // System.out.println(cert.getPublicKey().toString());
        trustStore.setCertificateEntry("jetty" + bis.available(), cert);
    }//from  w w w  .  ja v a2s.  c om

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, tmf.getTrustManagers(), null);
    SSLSocketFactory sslFactory = ctx.getSocketFactory();

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            if (0 == hostname.compareToIgnoreCase(url.getHost())) {
                return true;
            }
            return false;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(sslFactory);

    return urlConnection.getInputStream();
}

From source file:xyz.karpador.godfishbot.commands.MLPCommand.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 ww.ja va  2  s .  c om
        String urlString = "https://derpibooru.org/search.json?q="
                + URLEncoder.encode(params, "UTF-8").replace("%20", "+");
        URL url = new URL(urlString);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        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 totalHits = resultJson.getInt("total");
            if (totalHits < 1) {
                result.replyToId = message.getMessageId();
                result.text = "No results found.";
                return result;
            }
            int pageNumber = 1;
            if (totalHits > 20) // Generate a valid page number.
                pageNumber = Main.Random.nextInt((int) Math.ceil(totalHits / 20)) + 1;
            if (pageNumber > 1) {
                urlString += "&page=" + pageNumber;
                url = new URL(urlString);
                con = (HttpsURLConnection) url.openConnection();
                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 hits = resultJson.getJSONArray("search");
            int imageIndex = Main.Random.nextInt(hits.length());
            JSONObject img = hits.getJSONObject(imageIndex);
            result.imageUrl = "https:" + img.getString("image");
            if (result.imageUrl.toLowerCase().endsWith(".gif"))
                result.isGIF = true;
            if (knownImages.containsKey(result.imageUrl))
                result.mediaId = knownImages.get(result.imageUrl);
            result.text = "From derpibooru.org";
            //+ "(Source: " + img.getString("source_url") + ")";
            if (!img.isNull("source_url"))
                result.text += " (Source: " + img.getString("source_url") + ")";
        } else {
            result.text = "derpibooru.org returned error code " + con.getResponseCode() + ": "
                    + con.getResponseMessage();
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
        return null;
    }
    return result;
}

From source file:ezbake.deployer.publishers.SecurityServiceClient.java

/**
 * The applicationId is part of the REST call to the Security Service.
 * Returns an empty list if no certificates were found or throws exception if
 * something went wrong with Security Service communication.
 *//*from w ww.  java  2 s .  co m*/
@Override
public List<ArtifactDataEntry> get(String applicationId, String securityId) throws DeploymentException {
    try {
        ArrayList<ArtifactDataEntry> certList = new ArrayList<ArtifactDataEntry>();
        String endpoint = config.getSecurityServiceBasePath() + "/registrations/" + securityId + "/download";
        URL url = new URL(endpoint);
        HttpsURLConnection urlConn = openUrlConnection(url);
        urlConn.connect();

        // Read in tar file of certificates into byte array
        BufferedInputStream in = new BufferedInputStream(urlConn.getInputStream());
        // Create CertDataEntry list from tarFile byte array
        TarArchiveInputStream tarIn = new TarArchiveInputStream(in);
        TarArchiveEntry entry = tarIn.getNextTarEntry();
        while (entry != null) {
            if (!entry.isDirectory()) {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                IOUtils.copy(tarIn, bout);
                byte[] certData = bout.toByteArray();
                String certFileName = entry.getName().substring(entry.getName().lastIndexOf("/") + 1,
                        entry.getName().length());
                TarArchiveEntry tae = new TarArchiveEntry(
                        Files.get(SSL_CONFIG_DIRECTORY, securityId, certFileName));
                ArtifactDataEntry cde = new ArtifactDataEntry(tae, certData);
                certList.add(cde);
                bout.close();
            }

            entry = tarIn.getNextTarEntry();
        }
        tarIn.close();

        return certList;
    } catch (Exception e) {
        log.error("Unable to download certificates from security service.", e);
        throw new DeploymentException(
                "Unable to download certificates from security service. " + e.getMessage());
    }
}