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:com.wso2telco.MePinStatusRequest.java

public String call() {
    String allowStatus = null;/*w  w  w  .  j a  va2  s  .c o m*/

    String clientId = configurationService.getDataHolder().getMobileConnectConfig().getSessionUpdaterConfig()
            .getMePinClientId();
    String url = configurationService.getDataHolder().getMobileConnectConfig().getSessionUpdaterConfig()
            .getMePinUrl();
    url = url + "?transaction_id=" + transactionId + "&client_id=" + clientId + "";
    if (log.isDebugEnabled()) {
        log.info("MePIN Status URL : " + url);
    }
    String authHeader = "Basic " + configurationService.getDataHolder().getMobileConnectConfig()
            .getSessionUpdaterConfig().getMePinAccessToken();

    try {
        HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();

        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", authHeader);

        String resp = "";
        int statusCode = connection.getResponseCode();
        InputStream is;
        if ((statusCode == 200) || (statusCode == 201)) {
            is = connection.getInputStream();
        } else {
            is = connection.getErrorStream();
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String output;
        while ((output = br.readLine()) != null) {
            resp += output;
        }
        br.close();

        if (log.isDebugEnabled()) {
            log.debug("MePIN Status Response Code : " + statusCode + " " + connection.getResponseMessage());
            log.debug("MePIN Status Response : " + resp);
        }

        JsonObject responseJson = new JsonParser().parse(resp).getAsJsonObject();
        String respTransactionId = responseJson.getAsJsonPrimitive("transaction_id").getAsString();
        JsonPrimitive allowObject = responseJson.getAsJsonPrimitive("allow");

        if (allowObject != null) {
            allowStatus = allowObject.getAsString();
            if (Boolean.parseBoolean(allowStatus)) {
                allowStatus = "APPROVED";
                String sessionID = DatabaseUtils.getMePinSessionID(respTransactionId);
                DatabaseUtils.updateStatus(sessionID, allowStatus);
            }
        }

    } catch (IOException e) {
        log.error("Error while MePIN Status request" + e);
    } catch (SQLException e) {
        log.error("Error in connecting to DB" + e);
    }
    return allowStatus;
}

From source file:org.liberty.android.fantastischmemo.downloader.cram.CramDownloadHelper.java

/**
 * Get the response String from an url with optional auth token.
 *
 * @param url the request url/*from   ww  w.  j a va  2  s .  c o  m*/
 * @param authToken the oauth auth token.
 * @return the response in string.
 */
private String getResponseString(URL url, String authToken) throws IOException {
    if (!Strings.isNullOrEmpty(authToken)) {
        // TODO: Add oauth here
    }

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    if (conn.getResponseCode() / 100 >= 3) {
        String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
        throw new IOException(
                "Request: " + url + " HTTP response code is :" + conn.getResponseCode() + " Error: " + s);
    }
    return new String(IOUtils.toByteArray(conn.getInputStream()), "UTF-8");

}

From source file:org.schabi.newpipe.download.FileDownloader.java

/** AsyncTask impl: executed in background thread does the download */
@Override/*w  w w.ja  v a2  s  .  com*/
protected Void doInBackground(Void... voids) {
    HttpsURLConnection con = null;
    InputStream inputStream = null;
    FileOutputStream outputStream = null;
    try {
        con = NetCipher.getHttpsURLConnection(fileURL);
        int responseCode = con.getResponseCode();

        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {
            fileSize = con.getContentLength();
            inputStream = new BufferedInputStream(con.getInputStream());
            outputStream = new FileOutputStream(saveFilePath);

            int bufferSize = 8192;
            int downloaded = 0;

            int bytesRead = -1;
            byte[] buffer = new byte[bufferSize];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
                downloaded += bytesRead;
                if (downloaded % 50000 < bufferSize) {
                    publishProgress(downloaded);
                }
            }

            publishProgress(bufferSize);

        } else {
            Log.i(TAG, "No file to download. Server replied HTTP code: " + responseCode);
        }
    } catch (IOException e) {
        Log.e(TAG, "No file to download. Server replied HTTP code: ", e);
        e.printStackTrace();
    } finally {
        try {
            if (outputStream != null) {
                outputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (con != null) {
            con.disconnect();
        }
    }
    return null;
}

From source file:org.mule.modules.wechat.common.HttpsConnection.java

public Map<String, Object> post(String httpsURL, String json) throws Exception {
    // Setup connection
    String result = "";
    URL url = new URL(httpsURL);
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json; encoding=utf-8");
    con.setDoOutput(true);/*from   w  w  w. j  av a2  s  .  c om*/
    OutputStream ops = con.getOutputStream();
    ops.write(json.getBytes("UTF-8"));
    ops.flush();
    ops.close();

    // Call wechat
    InputStream ins = con.getInputStream();
    InputStreamReader isr = new InputStreamReader(ins, "UTF-8");
    BufferedReader in = new BufferedReader(isr);

    // Read result
    String inputLine;
    StringBuilder sb = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        sb.append((new JSONObject(inputLine)).toString());
    }
    result = sb.toString();
    in.close();

    // Convert JSON string to Map
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(result, new TypeReference<Map<String, Object>>() {
    });

    return map;
}

From source file:com.logger.TrackServlet.java

private String getJsonData(String ip) {
    String result = "";
    try {//from   www  .  ja v  a  2  s.co m
        URL url = new URL("https://stat.ripe.net/data/whois/data.json?resource=" + ip);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.connect();
        int status = connection.getResponseCode();
        if (status == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                result += line;
            }
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(TrackServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(TrackServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:io.fabric8.apiman.BearerTokenFilter.java

/**
 * Validates the bearer token with the kubernetes oapi and returns the username
 * if it is a valid token./*from  www . j  av  a2s . co  m*/
 * 
 * @param bearerHeader
 * @return username of the user to whom the token was issued to
 * @throws IOException - when the token is invalid, or oapi cannot be reached.
 */
protected String validateBearerToken(String bearerHeader) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    HttpsURLConnection con = (HttpsURLConnection) kubernetesOsapiUrl.openConnection();
    con.setRequestProperty("Authorization", bearerHeader);
    con.setConnectTimeout(10000);
    con.setReadTimeout(10000);
    con.setRequestProperty("Content-Type", "application/json");
    if (kubernetesTrustCert)
        TrustEverythingSSLTrustManager.trustAllSSLCertificates(con);
    con.connect();
    OAuthClientAuthorizationList userList = mapper.readValue(con.getInputStream(),
            OAuthClientAuthorizationList.class);
    String userName = userList.getItems().get(0).getMetadata().getName();
    return userName;
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse postWithBasicAuth(String uri, String requestQuery, String contentType,
        String userName, String password) throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        conn.setRequestProperty("Authorization", "Basic " + encode);
        conn.setDoOutput(true); // Triggers POST.
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length));
        conn.setUseCaches(false);/*  ww  w.  j  ava  2 s .c  o  m*/
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(requestQuery);
        conn.setReadTimeout(10000);
        conn.connect();
        System.out.println(conn.getRequestMethod());
        // Get the response
        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();
            }
            wr.flush();
            wr.close();
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:android.locationprivacy.algorithm.Webservice.java

@Override
public Location obfuscate(Location location) {
    // We do it this way to run network connection in main thread. This
    // way is not the normal one and does not comply to best practices,
    // but the main thread must wait for the obfuscation service reply anyway.
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);/*from  w w  w .  j  a v  a  2 s  .  co  m*/

    final String HOST_ADDRESS = configuration.getString("host");
    String username = configuration.getString("username");
    String password = configuration.getString("secret_password");

    Location newLoc = new Location(location);
    double lat = location.getLatitude();
    double lon = location.getLongitude();

    String urlString = HOST_ADDRESS;
    urlString += "?lat=" + lat;
    urlString += "&lon=" + lon;
    URL url;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        Log.e(TAG, "Error: could not build URL");
        Log.e(TAG, e.getMessage());
        return null;
    }
    HttpsURLConnection connection = null;
    JSONObject json = null;
    InputStream is = null;
    try {
        connection = (HttpsURLConnection) url.openConnection();
        connection.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        connection.setRequestProperty("Authorization",
                "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
        is = connection.getInputStream();

    } catch (IOException e) {
        Log.e(TAG, "Error while connectiong to " + url.toString());
        Log.e(TAG, e.getMessage());
        return null;
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    try {
        String line = reader.readLine();
        System.out.println("Line " + line);
        json = new JSONObject(line);
        newLoc.setLatitude(json.getDouble("lat"));
        newLoc.setLongitude(json.getDouble("lon"));
    } catch (IOException e) {
        Log.e(TAG, "Error: could not read from BufferedReader");
        Log.e(TAG, e.getMessage());
        return null;
    } catch (JSONException e) {
        Log.e(TAG, "Error: could not read from JSON");
        Log.e(TAG, e.getMessage());
        return null;
    }
    connection.disconnect();
    return newLoc;
}

From source file:org.openintents.lib.DeliciousApiHelper.java

public boolean addPost(String itemUrl, String description, String extended, String[] tags, boolean shared)
        throws java.io.IOException {

    String rpc = mAPI + "posts/add?";
    StringBuffer rpcBuf = new StringBuffer();
    StringBuffer tagsBuf = new StringBuffer();
    Element tag;/*from www.ja  v a 2s . c o  m*/
    URL u = null;

    String dateStamp;
    //TODO: timestamps

    if (description == null || description.equals("")) {
        description = "no description";
    }
    if (extended == null) {
        extended = new String();
    }

    try {

        rpcBuf.append("&url=" + itemUrl);
        rpcBuf.append("&description=" + URLEncoder.encode(description, "UTF8"));
        rpcBuf.append("&extendend=" + URLEncoder.encode(extended, "UTF8"));
        int tagsLen = tags.length;

        if (mAPI.equals(MAGNOLIA_API)) {
            //Magnolia uses comma as tag separator,..
            for (int i = 0; i < tagsLen; i++) {
                tagsBuf.append(URLEncoder.encode(tags[i]) + ",");
            }
        } else if (mAPI.equals(DELICIOUS_API)) {
            //while Delicious uses spaces
            for (int i = 0; i < tagsLen; i++) {
                tagsBuf.append(URLEncoder.encode(tags[i]) + " ");
            }
        }

        rpcBuf.append("&tags=" + tagsBuf.toString());
        if (shared) {
            rpcBuf.append("&shared=yes");
        } else {
            rpcBuf.append("&shared=no");
        }
        rpcBuf.append("&replace=no");

    } catch (Exception e) {
        Log.e(_TAG, "ERROR Encoding URL Parameters");
        e.printStackTrace();
    }

    rpc += rpcBuf.toString();

    //rpc=rpcBuf.toString();
    System.out.println("\n" + rpc + "\n");
    try {
        u = new URL(rpc);
    } catch (java.net.MalformedURLException mu) {
        System.out.println("Malformed URL>>" + mu.getMessage());
    }

    String s = "";
    try {
        javax.net.ssl.HttpsURLConnection connection = (javax.net.ssl.HttpsURLConnection) u.openConnection();
        //that's actualy pretty ugly to do, but a neede workaround for m5.rc15
        javax.net.ssl.HostnameVerifier v = new org.apache.http.conn.ssl.AllowAllHostnameVerifier();

        connection.setHostnameVerifier(v);

        //tru3 3v1l h4ack1ng ;)
        s = new Scanner(connection.getInputStream()).useDelimiter("\\Z").next();

    } catch (java.io.IOException ioe) {
        System.out.println("Error >>" + ioe.getMessage());
        Log.e(_TAG, "Error >>" + ioe.getMessage());

    } catch (Exception e) {
        Log.e(_TAG, "Error while excecuting HTTP method. URL is: " + u);
        System.out.println("Error while excecuting HTTP method. URL is: " + u);
        e.printStackTrace();
    }

    if (s.equals("<result code=\"done\" />")) {
        //   System.out.println("YEA!");
        return true;
    }
    //System.out.println(s);

    return false;
}

From source file:com.bytelightning.opensource.pokerface.HelloWorldScriptTest.java

@Test
public void testHelloWorld() throws IOException {
    URL obj = new URL("https://localhost:8443/helloWorlD.html"); // Intentional case mismatch
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("Accept-Language", "es, fr;q=0.8, en;q=0.7");
    int responseCode = con.getResponseCode();
    Assert.assertEquals("Valid reponse code", 200, responseCode);

    String contentType = con.getHeaderField("Content-Type");
    String charset = ScriptHelperImpl.GetCharsetFromContentType(contentType);
    Assert.assertTrue("Correct charset", charset.equalsIgnoreCase("utf-8"));

    try (Reader reader = new InputStreamReader(con.getInputStream(), charset)) {
        int aChar;
        StringBuilder sb = new StringBuilder();
        while ((aChar = reader.read()) != -1)
            sb.append((char) aChar);
        Assert.assertTrue("Acceptable language detected", sb.toString().contains("Hola mundo"));
    }//www  . j  a v a2 s.  c o m
}