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.apteligent.ApteligentJavaClient.java

/**
 * @param appID The app ID/*from   w  w  w . j  a v  a  2 s  .c  o m*/
 * @param hash The crash hash to retrieve
 * @return Array of impacted users
 */
public ArrayList<User> getCrashUsersAffected(String appID, String hash) {
    ArrayList<User> users = null;
    try {
        HttpsURLConnection conn = sendGetRequest(
                API_CRASH_USERS_AFFECTED.replace("{appId}", appID).replace("{hash}", hash));
        JsonFactory jsonFactory = new JsonFactory();
        JsonParser jp = jsonFactory.createParser(conn.getInputStream());
        ObjectMapper mapper = getObjectMapper();
        users = mapper.readValue(jp, new TypeReference<ArrayList<User>>() {
        });
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }
    return users;
}

From source file:de.btobastian.javacord.entities.impl.ImplCustomEmoji.java

@Override
public Future<byte[]> getEmojiAsByteArray(FutureCallback<byte[]> callback) {
    ListenableFuture<byte[]> future = api.getThreadPool().getListeningExecutorService()
            .submit(new Callable<byte[]>() {
                @Override//from ww w.  ja  v  a  2 s  .c om
                public byte[] call() throws Exception {
                    logger.debug("Trying to get emoji {} from server {}", ImplCustomEmoji.this, server);
                    URL url = getImageUrl();
                    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
                    conn.setRequestProperty("User-Agent", Javacord.USER_AGENT);
                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    byte[] buf = new byte[1024];
                    int n;
                    while (-1 != (n = in.read(buf))) {
                        out.write(buf, 0, n);
                    }
                    out.close();
                    in.close();
                    byte[] emoji = out.toByteArray();
                    logger.debug("Got emoji {} from server {} (size: {})", ImplCustomEmoji.this, server,
                            emoji.length);
                    return emoji;
                }
            });
    if (callback != null) {
        Futures.addCallback(future, callback);
    }
    return future;
}

From source file:xin.nic.sdk.registrar.util.HttpUtil.java

/**
 * ??HTTPS GET/*from w w w.  j a v a2s  .  co  m*/
 * 
 * @param url URL
 * @return 
 */
public static HttpResp doHttpsGet(URL url) {

    HttpsURLConnection conn = null;
    InputStream inputStream = null;
    Reader reader = null;

    try {
        // ???httphttps
        String protocol = url.getProtocol();
        if (!PROTOCOL_HTTPS.equals(protocol)) {
            throw new XinException("xin.error.url", "?https");
        }

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

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, tmArr, new SecureRandom());

        conn.setSSLSocketFactory(sc.getSocketFactory());

        // ?
        conn.setConnectTimeout(connTimeout);
        conn.setReadTimeout(readTimeout);
        conn.setDoOutput(true);
        conn.setDoInput(true);

        // UserAgent
        conn.setRequestProperty("User-Agent", "java-sdk");

        // ?
        conn.connect();

        // ?
        inputStream = conn.getInputStream();
        reader = new InputStreamReader(inputStream, charset);
        BufferedReader bufferReader = new BufferedReader(reader);
        StringBuilder stringBuilder = new StringBuilder();
        String inputLine = "";
        while ((inputLine = bufferReader.readLine()) != null) {
            stringBuilder.append(inputLine);
            stringBuilder.append("\n");
        }

        // 
        HttpResp resp = new HttpResp();
        resp.setStatusCode(conn.getResponseCode());
        resp.setStatusPhrase(conn.getResponseMessage());
        resp.setContent(stringBuilder.toString());

        // 
        return resp;
    } catch (MalformedURLException e) {
        throw new XinException("xin.error.url", "url:" + url + ", url?");
    } catch (IOException e) {
        throw new XinException("xin.error.http", String.format("IOException:%s", e.getMessage()));
    } catch (KeyManagementException e) {
        throw new XinException("xin.error.url", "url:" + url + ", url?");
    } catch (NoSuchAlgorithmException e) {
        throw new XinException("xin.error.url", "url:" + url + ", url?");
    } finally {

        if (reader != null) {
            try {
                reader.close();

            } catch (IOException e) {
                throw new XinException("xin.error.url", "url:" + url + ", reader");
            }
        }

        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new XinException("xin.error.url", "url:" + url + ", ?");
            }
        }

        // 
        quietClose(conn);
    }
}

From source file:com.starr.smartbuilds.service.DataService.java

public void getItemsDataFromRiotAPI() throws IOException, ParseException {
    String line;/*from  w  w  w  .  j av a  2s . co m*/
    String result = "";
    URL url = new URL("https://global.api.pvp.net/api/lol/static-data/euw/v1.2/item?itemListData=tags&api_key="
            + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    getItemsFromData(result);
}

From source file:com.starr.smartbuilds.service.DataService.java

public void getChampionsDataFromRiotAPI() throws IOException, ParseException {
    String line;/*w  w  w .  ja  v  a 2  s  . co m*/
    String result = "";
    URL url = new URL(
            "https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion?api_key=" + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    getChampionsFromData(result);
}

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

@SuppressWarnings("unchecked")
public static void authServer17(String hash) throws IOException {
    URL url;//  ww w  .  ja  va2 s .c om
    String username;
    String accessToken;
    try {
        if (loginDetails == null) {
            throw new IOException("Not logged in");
        }

        try {
            username = URLEncoder.encode(getUsername(), "UTF-8");
            accessToken = URLEncoder.encode(getAccessToken(), "UTF-8");
            hash = URLEncoder.encode(hash, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IOException("Username/password encoding error", e);
        }

        String urlString;
        urlString = sessionServer17;
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new IOException("Auth server URL error", e);
    }
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setDoOutput(true);
    con.setInstanceFollowRedirects(false);
    con.setReadTimeout(5000);
    con.setConnectTimeout(5000);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.connect();

    JSONObject obj = new JSONObject();
    obj.put("accessToken", accessToken);
    obj.put("selectedProfile", loginDetails.get("selectedProfile"));
    obj.put("serverId", hash);
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8));
    try {
        obj.writeJSONString(writer);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        if (writer != null) {
            writer.close();
            con.disconnect();
            return;
        }
    }
    if (con.getResponseCode() != 200) {
        throw new IOException("Unable to verify username, please restart proxy");
    }
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
    try {
        String reply = reader.readLine();
        if (reply != null) {
            throw new IOException("Auth server replied (" + reply + ")");
        }
    } finally {
        reader.close();
        con.disconnect();
    }
}

From source file:com.starr.smartbuilds.service.DataService.java

private String getSummonerIdDataFromRiotAPI(String region, String summonerName)
        throws MalformedURLException, IOException, ParseException {
    String line;// w  w  w  .j a v a  2  s .c om
    String result = "";
    URL url = new URL("https://" + region + ".api.pvp.net/api/lol/" + region + "/v1.4/summoner/by-name/"
            + summonerName + "?api_key=" + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    return result;
}

From source file:com.starr.smartbuilds.service.DataService.java

private String getSummonerDataFromRiotAPI(String region, Long summonerID)
        throws MalformedURLException, IOException {
    String line;//  www. ja  v a2s .  co m
    String result = "";
    URL url = new URL("https://" + region + ".api.pvp.net/api/lol/" + region + "/v2.5/league/by-summoner/"
            + summonerID + "/entry?api_key=" + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    return result;
}

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

public static HttpsResponse putWithBasicAuth(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", "");
        ;/*ww w  .  j a v  a 2 s .  c o  m*/
        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);
        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();
        // 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:com.emuneee.nctrafficcams.tasks.GetLatestCameras.java

private String getLatestUpdateTime() {
    HttpsURLConnection connection = null;
    BufferedReader reader = null;
    String updateDatetime = null;

    try {//from  w  w w.  j  a v  a2 s. co m
        StringBuilder updateStr = new StringBuilder();
        connection = HttpUtils.getAuthUrlConnection(mBaseUrl + sUpdatePath, mContext);
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = null;

        while ((line = reader.readLine()) != null) {
            updateStr.append(line);
        }
        Log.d(TAG, "Content Size: " + updateStr.length());
        Log.d(TAG, "Response Code: " + connection.getResponseCode());
        JSONObject updateObj = new JSONObject(updateStr.toString());
        updateDatetime = updateObj.getString("updated");
    } catch (Exception e) {
        Log.e(TAG, "Error getting latest update time");
        Log.e(TAG, e.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                Log.w(TAG, "Error retrieving latest update time");
                Log.w(TAG, e.getMessage());
            }
        }
    }

    return updateDatetime;
}