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.omertron.pushoverapi.PushoverApi.java

/**
 * Sends a raw bit of text via POST to PushoverApi.
 *
 * @param message/*  ww  w .  jav  a2 s  . c  om*/
 * @return JSON reply from PushoverApi.
 * @throws IOException
 */
private String sendToPushover(String message) throws IOException {
    URL pushoverUrl = new URL(PUSHOVER_URL);

    if (isDebug)
        System.out.println("Pushing with URL: " + message);

    HttpsURLConnection connection = (HttpsURLConnection) pushoverUrl.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);

    OutputStream outputStream = null;
    try {
        outputStream = connection.getOutputStream();
        outputStream.write(message.getBytes(Charset.forName("UTF-8")));
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }

    InputStreamReader isr = null;
    BufferedReader br = null;
    StringBuilder output = new StringBuilder();
    try {
        isr = new InputStreamReader(connection.getInputStream());
        br = new BufferedReader(isr);
        connection.disconnect();

        String outputCache;
        while ((outputCache = br.readLine()) != null) {
            output.append(outputCache);
        }
    } finally {
        if (isr != null) {
            isr.close();
        }
        if (br != null) {
            br.close();
        }
    }
    return output.toString();
}

From source file:com.glaf.core.util.http.HttpUtils.java

/**
 * ?https?/* www .j  a  v a  2s . c om*/
 * 
 * @param requestUrl
 *            ?
 * @param method
 *            ?GET?POST
 * @param content
 *            ???
 * @return
 */
public static String doRequest(String requestUrl, String method, String content, boolean isSSL) {
    log.debug("requestUrl:" + requestUrl);
    HttpsURLConnection conn = null;
    InputStream inputStream = null;
    BufferedReader bufferedReader = null;
    InputStreamReader inputStreamReader = null;
    StringBuffer buffer = new StringBuffer();
    try {
        URL url = new URL(requestUrl);
        conn = (HttpsURLConnection) url.openConnection();
        if (isSSL) {
            // SSLContext??
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // SSLContextSSLSocketFactory
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            conn.setSSLSocketFactory(ssf);
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        // ?GET/POST
        conn.setRequestMethod(method);
        if ("GET".equalsIgnoreCase(method)) {
            conn.connect();
        }

        // ????
        if (StringUtils.isNotEmpty(content)) {
            OutputStream outputStream = conn.getOutputStream();
            // ????
            outputStream.write(content.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();
        }

        // ???
        inputStream = conn.getInputStream();
        inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }

        log.debug("response:" + buffer.toString());

    } catch (ConnectException ce) {
        ce.printStackTrace();
        log.error(" http server connection timed out.");
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error("http request error:{}", ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(bufferedReader);
        IOUtils.closeQuietly(inputStreamReader);
        if (conn != null) {
            conn.disconnect();
        }
    }
    return buffer.toString();
}

From source file:com.github.gorbin.asne.linkedin.LinkedInSocialNetwork.java

private void getAllFriends(String urlString, final ArrayList<SocialPerson> socialPersons,
        final ArrayList<String> ids, String token) throws Exception {
    URL url = new URL(urlString);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    checkConnectionErrors(connection);// ww w .jav  a2s.com
    InputStream inputStream = connection.getInputStream();
    String response = streamToString(inputStream);
    JSONObject jsonObject = (JSONObject) new JSONTokener(response).nextValue();

    int jsonStart = 0, jsonCount = 0, jsonTotal = 0;
    String nextToken = null;
    if (jsonObject.has("_start")) {
        jsonStart = jsonObject.getInt("_start");
    }
    if (jsonObject.has("_count")) {
        jsonCount = jsonObject.getInt("_count");
    }
    if (jsonObject.has("_total")) {
        jsonTotal = jsonObject.getInt("_total");
    }
    int start = jsonStart + jsonCount;
    if (jsonTotal > 0 && start > 0 && jsonCount > 0 && jsonTotal > start) {
        nextToken = LINKEDIN_V1_API + "/people/~/connections" + RequestGetFriendsAsyncTask.fields
                + "?oauth2_access_token=" + token + FORMAT_JSON + "&start=" + start + "&count="
                + RequestGetFriendsAsyncTask.count;
    }
    JSONArray jsonResponse = jsonObject.getJSONArray("values");
    int length = jsonResponse.length();
    for (int i = 0; i < length; i++) {
        SocialPerson socialPerson = new SocialPerson();
        getSocialPerson(socialPerson, jsonResponse.getJSONObject(i));
        socialPersons.add(socialPerson);
        ids.add(jsonResponse.getJSONObject(i).getString("id"));
    }

    if ((nextToken != null) && (!TextUtils.isEmpty(nextToken))) {
        getAllFriends(nextToken, socialPersons, ids, token);
    }
}

From source file:com.dsna.android.main.MainActivity.java

private void getPublicKeysFromServer()
        throws InvalidCertificateException, IOException, KeyManagementException, NoSuchAlgorithmException {
    KeyStore dsnaKeyStore = loadLocalTrustKeystore();
    HttpsURLConnection urlConnection = NetworkUtil.establishHttpsConnection(publicKeyURL, dsnaKeyStore);
    String encodedPublicKeys = FileUtil.readString(urlConnection.getInputStream());
    urlConnection.disconnect();/*w  w  w.jav a2 s  .  co  m*/
    publicKeys = ASN1Util.extractPublicKey(ASN1Util.decodeIBESysPublicParams(encodedPublicKeys));
}

From source file:com.esri.geoevent.test.tools.GetMapServiceCountRunnable.java

private int getMsLayerCount(String url) {
    int cnt = -1;

    try {/*from  w ww.j  a  va 2 s  .com*/
        URL obj = new URL(url + "/query");
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");

        con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Accept", "text/plain");

        String urlParameters = "where=" + URLEncoder.encode("1=1", "UTF-8") + "&returnCountOnly="
                + URLEncoder.encode("true", "UTF-8") + "&f=" + URLEncoder.encode("json", "UTF-8");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

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

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

        //print result
        String jsonString = response.toString();

        JSONTokener tokener = new JSONTokener(jsonString);

        JSONObject root = new JSONObject(tokener);

        cnt = root.getInt("count");

    } catch (Exception e) {
        cnt = -2;
    } finally {
        return cnt;
    }

}

From source file:com.dsna.android.main.MainActivity.java

private void getSecretKeysFromServer() throws InvalidCertificateException, IOException,
        UnsupportedFormatException, KeyManagementException, NoSuchAlgorithmException {
    // Load publickey from file
    String mySecretKeyUrl = secretKeyURL + "?" + idParams + "=" + mUsername;
    KeyStore dsnaKeyStore = loadLocalTrustKeystore();
    HttpsURLConnection urlConnection = NetworkUtil.establishHttpsConnection(mySecretKeyUrl, dsnaKeyStore);
    String encodedPrivateKeys = FileUtil.readString(urlConnection.getInputStream());
    urlConnection.disconnect();//from  w w w. ja  v  a2  s . c o  m
    secretKeys = ASN1Util.extractClientSecretKey(ASN1Util.decodeIBEClientSecretParams(encodedPrivateKeys),
            getPublicKeys());
}

From source file:com.microsoft.speech.tts.Authentication.java

private void HttpPost(String AccessTokenUri, String apiKey) {
    InputStream inSt = null;/*  w  w  w . ja  va2 s.com*/
    HttpsURLConnection webRequest = null;

    this.accessToken = null;
    //Prepare OAuth request
    try {
        URL url = new URL(AccessTokenUri);
        webRequest = (HttpsURLConnection) url.openConnection();
        webRequest.setDoInput(true);
        webRequest.setDoOutput(true);
        webRequest.setConnectTimeout(5000);
        webRequest.setReadTimeout(5000);
        webRequest.setRequestProperty("Ocp-Apim-Subscription-Key", apiKey);
        webRequest.setRequestMethod("POST");

        String request = "";
        byte[] bytes = request.getBytes();
        webRequest.setRequestProperty("content-length", String.valueOf(bytes.length));
        webRequest.connect();

        DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream());
        dop.write(bytes);
        dop.flush();
        dop.close();

        inSt = webRequest.getInputStream();
        InputStreamReader in = new InputStreamReader(inSt);
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }

        bufferedReader.close();
        in.close();
        inSt.close();
        webRequest.disconnect();

        this.accessToken = strBuffer.toString();

    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}

From source file:org.wso2.carbon.appmgt.sampledeployer.http.HttpHandler.java

public String doPostHttps(String backEnd, String payload, String your_session_id, String contentType)
        throws IOException {
    URL obj = new URL(backEnd);

    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    if (!your_session_id.equals("")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + your_session_id);
    }/*from   w  ww. j  av  a2 s  . co  m*/
    if (!contentType.equals("")) {
        con.setRequestProperty("Content-Type", contentType);
    }
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        if (your_session_id.equals("")) {
            String session_id = response.substring((response.lastIndexOf(":") + 3),
                    (response.lastIndexOf("}") - 2));
            return session_id;
        } else if (your_session_id.equals("header")) {
            return con.getHeaderField("Set-Cookie");
        }

        return response.toString();
    }
    return null;
}

From source file:com.microsoft.speech.tts.OxfordAuthentication.java

private void HttpPost(String AccessTokenUri, String requestDetails) {
    InputStream inSt = null;//from  w w w  . ja  va2s .c om
    HttpsURLConnection webRequest = null;

    this.token = null;
    //Prepare OAuth request
    try {
        URL url = new URL(AccessTokenUri);
        webRequest = (HttpsURLConnection) url.openConnection();
        webRequest.setDoInput(true);
        webRequest.setDoOutput(true);
        webRequest.setConnectTimeout(5000);
        webRequest.setReadTimeout(5000);
        webRequest.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        webRequest.setRequestMethod("POST");

        byte[] bytes = requestDetails.getBytes();
        webRequest.setRequestProperty("content-length", String.valueOf(bytes.length));
        webRequest.connect();

        DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream());
        dop.write(bytes);
        dop.flush();
        dop.close();

        inSt = webRequest.getInputStream();
        InputStreamReader in = new InputStreamReader(inSt);
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }

        bufferedReader.close();
        in.close();
        inSt.close();
        webRequest.disconnect();

        // parse the access token from the json format
        String result = strBuffer.toString();
        JSONObject jsonRoot = new JSONObject(result);
        this.token = new OxfordAccessToken();

        if (jsonRoot.has("access_token")) {
            this.token.access_token = jsonRoot.getString("access_token");
        }

        if (jsonRoot.has("token_type")) {
            this.token.token_type = jsonRoot.getString("token_type");
        }

        if (jsonRoot.has("expires_in")) {
            this.token.expires_in = jsonRoot.getString("expires_in");
        }

        if (jsonRoot.has("scope")) {
            this.token.scope = jsonRoot.getString("scope");
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}

From source file:org.openmrs.module.rheashradapter.util.GenerateORU_R01Alert.java

public String callQueryFacility(String msg, Encounter e)
        throws IOException, TransformerFactoryConfigurationError, TransformerException {

    Cohort singlePatientCohort = new Cohort();
    singlePatientCohort.addMember(e.getPatient().getId());

    Map<Integer, String> patientIdentifierMap = Context.getPatientSetService()
            .getPatientIdentifierStringsByType(singlePatientCohort, Context.getPatientService()
                    .getPatientIdentifierTypeByName(RHEAHL7Constants.IDENTIFIER_TYPE));

    // Setup connection
    String id = patientIdentifierMap.get(patientIdentifierMap.keySet().iterator().next());
    URL url = new URL(hostname + "/ws/rest/v1/alerts");
    System.out.println("full url " + url);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);// w w w.j  a va  2 s.co m
    conn.setRequestMethod("POST");
    conn.setDoInput(true);

    // This is important to get the connection to use our trusted
    // certificate
    conn.setSSLSocketFactory(sslFactory);

    addHTTPBasicAuthProperty(conn);
    // conn.setConnectTimeout(timeOut);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    log.error("body" + msg);
    out.write(msg);
    out.close();
    conn.connect();
    String headerValue = conn.getHeaderField("http.status");

    // Test response code
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }

    String result = convertInputStreamToString(conn.getInputStream());
    conn.disconnect();

    return result;
}