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.mb.ext.web.controller.UserController.java

@RequestMapping(value = "/getAirQuality", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.CREATED)/*from   w w  w .j  a  va  2s  .  co  m*/
@ResponseBody
public ResultDTO getAirQuality() {
    // AirQualityDTO airQualityDTO = new AirQualityDTO();
    ResultDTO resultDTO = new ResultDTO();
    String result = null;
    try {
        String httpUrl = Constants.WEATHER_URL;
        BufferedReader reader = null;
        InputStream is = null;
        StringBuffer sbf = new StringBuffer();
        try {
            URL url = new URL(httpUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            is = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }

            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reader.close();
            is.close();
        }

        resultDTO.setCode("0");
        resultDTO.setMessage("Get air quality successfully");

    } catch (Exception e) {
        resultDTO.setCode("1");
        resultDTO.setMessage(e.getMessage());
    }
    resultDTO.setBody(result);
    return resultDTO;
}

From source file:com.apteligent.ApteligentJavaClient.java

/*********************************************************************************************************************/

private Token auth(String email, String password) throws IOException {
    String urlParameters = "grant_type=password&username=" + email + "&password=" + password;

    URL obj = new URL(API_TOKEN);
    HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
    conn.setDoOutput(true);/*from  ww w.  ja  va 2  s. c om*/
    conn.setDoInput(true);

    //add request header
    String basicAuth = new String(Base64.encodeBytes(apiKey.getBytes()));
    conn.setRequestProperty("Authorization", String.format("Basic %s", basicAuth));
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
    conn.setRequestMethod("POST");

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

    // read token
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser jp = jsonFactory.createParser(conn.getInputStream());
    ObjectMapper mapper = getObjectMapper();
    Token token = mapper.readValue(jp, Token.class);

    return token;
}

From source file:com.github.abilityapi.abilityapi.external.Metrics.java

/**
 * Sends the data to the bStats server.//ww w. ja va 2 s. co m
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JsonObject data) throws Exception {
    Validate.notNull(data, "Data cannot be null");
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}

From source file:online.privacy.PrivacyOnlineApiRequest.java

private JSONObject makeAPIRequest(String method, String endPoint, String jsonPayload)
        throws IOException, JSONException {
    InputStream inputStream = null;
    OutputStream outputStream = null;
    String apiUrl = "https://api.privacy.online";
    String apiKey = this.context.getString(R.string.privacy_online_api_key);
    String keyString = "?key=" + apiKey;

    int payloadSize = jsonPayload.length();

    try {//from  w w w  . j a  va2 s . c  o m
        URL url = new URL(apiUrl + endPoint + keyString);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        // Sec 5 second connect/read timeouts
        connection.setReadTimeout(5000);
        connection.setConnectTimeout(5000);
        connection.setRequestMethod(method);
        connection.setRequestProperty("Content-Type", "application/json");

        if (payloadSize > 0) {
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setFixedLengthStreamingMode(payloadSize);
        }

        // Initiate the connection
        connection.connect();

        // Write the payload if there is one.
        if (payloadSize > 0) {
            outputStream = connection.getOutputStream();
            outputStream.write(jsonPayload.getBytes("UTF-8"));
        }

        // Get the response code ...
        int responseCode = connection.getResponseCode();
        Log.e(LOG_TAG, "Response code: " + responseCode);

        switch (responseCode) {
        case HttpsURLConnection.HTTP_OK:
            inputStream = connection.getInputStream();
            break;
        case HttpsURLConnection.HTTP_FORBIDDEN:
            inputStream = connection.getErrorStream();
            break;
        case HttpURLConnection.HTTP_NOT_FOUND:
            inputStream = connection.getErrorStream();
            break;
        case HttpsURLConnection.HTTP_UNAUTHORIZED:
            inputStream = connection.getErrorStream();
            break;
        default:
            inputStream = connection.getInputStream();
            break;
        }

        String responseContent = "{}"; // Default to an empty object.
        if (inputStream != null) {
            responseContent = readInputStream(inputStream, connection.getContentLength());
        }

        JSONObject responseObject = new JSONObject(responseContent);
        responseObject.put("code", responseCode);

        return responseObject;

    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

/**
 * Tries to download the contents of the provided url using not commercially validated CA certificate from chosen provider.
 *
 * @param url_string as a string/*from  w  ww  . ja  v  a  2s  .  c o m*/
 * @return an empty string if it fails, the url content if not.
 */
private String downloadWithProviderCA(String url_string) {
    String json_file_content = "";

    try {
        URL url = new URL(url_string);
        // Tell the URLConnection to use a SocketFactory from our SSLContext
        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setSSLSocketFactory(getProviderSSLSocketFactory());
        if (!LeapSRPSession.getToken().isEmpty())
            urlConnection.addRequestProperty(LeapSRPSession.AUTHORIZATION_HEADER,
                    "Token token=" + LeapSRPSession.getToken());
        json_file_content = new Scanner(urlConnection.getInputStream()).useDelimiter("\\A").next();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnknownHostException e) {
        e.printStackTrace();
        json_file_content = formatErrorMessage(R.string.server_unreachable_message);
    } catch (IOException e) {
        // The downloaded certificate doesn't validate our https connection.
        json_file_content = formatErrorMessage(R.string.certificate_error);
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchElementException e) {
        e.printStackTrace();
        json_file_content = formatErrorMessage(R.string.server_unreachable_message);
    }
    return json_file_content;
}

From source file:org.belio.service.gateway.AirtelCharging.java

private String sendXmlOverPost(String url, String xml) {
    StringBuffer result = new StringBuffer();
    try {/*  w w  w .  j  ava2s  . c o  m*/
        Launcher.LOG.info("======================xml==============");

        Launcher.LOG.info(xml.toString());

        //            String userPassword = "roamtech_KE:roamtech _KE!ibm123";
        //            URL url2 = new URL("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1");

        String userPassword = "" + networkproperties.getProperty("air_info_u") + ":"
                + networkproperties.getProperty("air_info_p");
        URL url2 = new URL(url);

        // URLConnection urlc =  url.openConnection();
        URLConnection urlc = url2.openConnection();
        HttpsURLConnection conn = (HttpsURLConnection) urlc;
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("SOAPAction", "run");

        //            urlc.setDoOutput(true);
        //            urlc.setUseCaches(false);
        //            urlc.setAllowUserInteraction(false);
        conn.setRequestProperty("Authorization", "Basic " + new Base64().encode(userPassword.getBytes()));
        conn.setRequestProperty("Content-Type", "text/xml");

        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        // Write post data
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(xml);
        out.flush();
        out.close();
        BufferedReader aiResult = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        StringBuffer responseMessage = new StringBuffer();
        while ((line = aiResult.readLine()) != null) {
            responseMessage.append(line);
        }
        System.out.println(responseMessage);

        //urlc.s("POST");  
        //  urlc.setRequestProperty("SOAPAction", SOAP_ACTION);

        urlc.connect();

    }

    catch (MalformedURLException ex) {
        Logger.getLogger(AirtelCharging.class

                .getName()).log(Level.SEVERE, null, ex);
    }

    catch (IOException ex) {
        Logger.getLogger(AirtelCharging.class

                .getName()).log(Level.SEVERE, null, ex);
    }
    return result.toString();

    //        try {
    //            // String url = "https://selfsolve.apple.com/wcResults.do";
    //            HttpClient client = new DefaultHttpClient();
    //            HttpPost post = new HttpPost("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1");
    //            // add header
    //            post.setHeader("User-Agent", USER_AGENT);
    //            post.setHeader("Content-type:", " text/xml");
    //            post.setHeader("charset", "utf-8");
    //            post.setHeader("Accept:", ",text/xml");
    //            post.setHeader("Cache-Control:", " no-cache");
    //            post.setHeader("Pragma:", " no-cache");
    //            post.setHeader("SOAPAction:", "run");
    //            post.setHeader("Content-length:", "xml");
    //            
    ////            String encoding = new Base64().encode((networkproperties.getProperty("air_charge_n") + ":"
    ////                    + networkproperties.getProperty("air_charge_p")).getBytes());
    //            String encoding = new Base64().encode( ("roamtech_KE:roamtech _KE!ibm123").getBytes());
    //            
    //            post.setHeader("Authorization", "Basic " + encoding);
    //
    //            // post.setHeader("Authorization: Basic ", "base64_encode(credentials)");
    //            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    //            
    //            urlParameters.add(new BasicNameValuePair("xml", xml));
    //            
    //            System.out.println("\n============================ : " + url);
    //
    ////            urlParameters.add(new BasicNameValuePair("srcCode", ""));
    ////            urlParameters.add(new BasicNameValuePair("phone", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentId", ""));
    ////            urlParameters.add(new BasicNameValuePair("itemName", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentDescription", ""));
    ////            urlParameters.add(new BasicNameValuePair("actualPrice", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentMediaType", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentUrl", ""));
    //            post.setEntity(new UrlEncodedFormEntity(urlParameters));
    //            
    //            HttpResponse response = client.execute(post);
    //            Launcher.LOG.info("\nSending 'POST' request to URL : " + url);
    //            Launcher.LOG.info("Post parameters : " + post.getEntity());
    //            Launcher.LOG.info("Response Code : "
    //                    + response.getStatusLine().getStatusCode());
    //            
    //            BufferedReader rd = new BufferedReader(
    //                    new InputStreamReader(response.getEntity().getContent()));
    //            
    //            String line = "";
    //            while ((line = rd.readLine()) != null) {
    //                result.append(line);
    //            }
    //            
    //            System.out.println(result.toString());
    //        } catch (UnsupportedEncodingException ex) {
    //            Launcher.LOG.info(ex.getMessage());
    //        } catch (IOException ex) {
    //            Launcher.LOG.info(ex.getMessage());
    //        }
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

private String downloadWithCommercialCA(String url_string, String ca_cert_fingerprint) {
    String result = "";

    int seconds_of_timeout = 2;
    String[] pins = new String[] { ca_cert_fingerprint };
    try {/* www  . j ava  2s .co m*/
        URL url = new URL(url_string);
        HttpsURLConnection connection = PinningHelper.getPinnedHttpsURLConnection(Dashboard.getContext(), pins,
                url);
        connection.setConnectTimeout(seconds_of_timeout * 1000);
        if (!LeapSRPSession.getToken().isEmpty())
            connection.addRequestProperty(LeapSRPSession.AUTHORIZATION_HEADER,
                    "Token token = " + LeapSRPSession.getToken());
        result = new Scanner(connection.getInputStream()).useDelimiter("\\A").next();
    } catch (IOException e) {
        if (e instanceof SSLHandshakeException)
            result = formatErrorMessage(R.string.error_security_pinnedcertificate);
        else
            result = formatErrorMessage(R.string.error_io_exception_user_message);
    }

    return result;
}

From source file:br.com.intelidev.dao.DadosDao.java

public List<Dados> get_stream_data(String stream_api, String user, String pass) {

    HttpsURLConnection conn = null;
    List<Dados> list_return = new ArrayList<>();
    int i;/*from  www  .  ja va2  s.c o m*/

    try {
        // Create url to the Device Cloud server for a given web service request
        //00000000-00000000-00409DFF-FF6064F8/xbee.analog/[00:13:A2:00:40:E6:5A:88]!/AD1
        ObjectMapper mapper = new ObjectMapper();
        URL url = new URL("https://devicecloud.digi.com/ws/v1/streams/history/" + stream_api);
        //URL url = new URL("https://devicecloud.digi.com/ws/v1/streams/history/00000000-00000000-00409DFF-FF6064F8/xbee.analog/[00:13:A2:00:40:E6:5A:88]!/AD1");
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("GET");

        // Build authentication string
        String userpassword = user + ":" + pass;
        System.out.println(userpassword);

        // can change this to use a different base64 encoder
        String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim();

        // set request headers
        conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
        // Get input stream from response and convert to String
        InputStream is = conn.getInputStream();

        Scanner isScanner = new Scanner(is);
        StringBuffer buf = new StringBuffer();
        while (isScanner.hasNextLine()) {
            buf.append(isScanner.nextLine() + "\n");
        }
        String responseContent = buf.toString();

        // add line returns between tags to make it a bit more readable
        responseContent = responseContent.replaceAll("><", ">\n<");

        // Output response to standard out
        System.out.println(responseContent);
        // Convert JSON string to Object
        StreamDados stream = mapper.readValue(responseContent, StreamDados.class);
        //System.out.println(stream.getList());
        System.out.println(stream.getList().size());
        for (i = 0; i < stream.getList().size(); i++) {
            list_return.add(stream.getList().get(i));
            //System.out.println("ts: "+ stream.getList().get(i).getTimestamp() + "Value: " + stream.getList().get(i).getValue());

        }

    } catch (Exception e) {
        // Print any exceptions that occur
        System.out.println("br.com.intelidev.dao.DadosDao.get_stream_data() e" + e);
    } finally {
        if (conn != null)
            conn.disconnect();
    }

    return list_return;
}

From source file:com.google.android.apps.santatracker.presentquest.PlacesIntentService.java

private ArrayList<LatLng> fetchPlacesFromAPI(LatLng center, int radius) {
    ArrayList<LatLng> places = new ArrayList<>();
    radius = Math.min(radius, 50000); // Max accepted radius is 50km.

    try {//  w  ww. j  a  v  a  2s . c om
        InputStream is = null;
        URL url = new URL(getString(R.string.places_api_url) + "?location=" + center.latitude + ","
                + center.longitude + "&radius=" + radius);

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);

        // Pass package name and signature as part of request
        String packageName = getPackageName();
        String signature = getAppSignature();

        conn.setRequestProperty("X-App-Package", packageName);
        conn.setRequestProperty("X-App-Signature", signature);

        conn.connect();
        int response = conn.getResponseCode();
        if (response != 200) {
            Log.e(TAG, "Places API HTTP error: " + response + " / " + url);
        } else {
            BufferedReader reader;
            StringBuilder builder = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            for (String line; (line = reader.readLine()) != null;) {
                builder.append(line);
            }
            JSONArray resultsJson = (new JSONObject(builder.toString())).getJSONArray("results");
            for (int i = 0; i < resultsJson.length(); i++) {
                JSONObject latLngJson = ((JSONObject) resultsJson.get(i)).getJSONObject("geometry")
                        .getJSONObject("location");
                places.add(new LatLng(latLngJson.getDouble("lat"), latLngJson.getDouble("lng")));
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Exception parsing places API: " + e.toString());
    }

    return places;
}

From source file:org.talend.components.marketo.runtime.client.MarketoBulkExecClient.java

public BulkImportResult executePostFileRequest(Class<?> resultClass, String filePath) throws MarketoException {
    String boundary = "Talend_tMarketoBulkExec_" + String.valueOf(System.currentTimeMillis());
    try {//from  w w  w. j  a v a 2 s.  c  o m
        URL url = new URL(current_uri.toString());
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        urlConn.setRequestProperty("accept", "text/json");
        urlConn.setDoOutput(true);
        String requestBody = buildRequest(filePath); // build the request body
        PrintWriter wr = new PrintWriter(new OutputStreamWriter(urlConn.getOutputStream()));
        wr.append("--" + boundary + "\r\n");
        wr.append("Content-Disposition: form-data; name=\"file\";filename=\"" + filePath + "\";\r\n");
        wr.append("Content-type: text/plain; charset=\"utf-8\"\r\n");
        wr.append("Content-Transfer-Encoding: text/plain\r\n");
        wr.append("MIME-Version: 1.0\r\n");
        wr.append("\r\n");
        wr.append(requestBody);
        wr.append("\r\n");
        wr.append("--" + boundary);
        wr.flush();
        wr.close();
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            InputStream inStream = urlConn.getInputStream();
            InputStreamReader reader = new InputStreamReader(inStream);
            Gson gson = new Gson();
            return (BulkImportResult) gson.fromJson(reader, resultClass);
        } else {
            LOG.error("POST request failed: {}", responseCode);
            throw new MarketoException(REST, responseCode,
                    "Request failed! Please check your request setting!");
        }
    } catch (IOException e) {
        LOG.error("POST request failed: {}", e.getMessage());
        throw new MarketoException(REST, e.getMessage());
    }
}