Example usage for javax.net.ssl HttpsURLConnection setDoInput

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

Introduction

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

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

Sets the value of the doInput field for this URLConnection to the specified value.

Usage

From source file:net.mms_projects.copy_it.server.push.android.GCMRunnable.java

public void run() {
    try {/*from   ww w. j  a va 2 s  .c  o  m*/
        URL url = new URL(GCM_URL);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod(POST);
        conn.setRequestProperty(CONTENT_TYPE, Page.ContentTypes.JSON_TYPE);
        conn.setRequestProperty(AUTHORIZATION, KEY);
        final String output_json = full.toString();
        System.err.println("Input json: " + output_json);
        conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(output_json.length()));
        conn.setDoOutput(true);
        conn.setDoInput(true);
        DataOutputStream outputstream = new DataOutputStream(conn.getOutputStream());
        outputstream.writeBytes(output_json);
        outputstream.close();
        DataInputStream input = new DataInputStream(conn.getInputStream());
        StringBuilder builder = new StringBuilder(input.available());
        for (int c = input.read(); c != -1; c = input.read())
            builder.append((char) c);
        input.close();
        output = new JSONObject(builder.toString());
        System.err.println("Output json: " + output.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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  ww .j  av a  2  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:com.alvexcore.share.ShareExtensionRegistry.java

public ExtensionUpdateInfo checkForUpdates(String extensionId, String shareId, Map<String, String> shareHashes,
        String shareVersion, String repoId, Map<String, String> repoHashes, String repoVersion,
        String licenseId) throws Exception {
    // search for extension
    DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance();
    xmlFact.setNamespaceAware(true);/*from  w  w w  .j  av  a2s.c o  m*/
    xmlBuilder = xmlFact.newDocumentBuilder();

    // build query
    Document queryXML = xmlBuilder.newDocument();
    Element rootElement = queryXML.createElement("extension");
    queryXML.appendChild(rootElement);
    Element el = queryXML.createElement("license-id");
    el.appendChild(queryXML.createTextNode(licenseId));
    rootElement.appendChild(el);
    el = queryXML.createElement("id");
    el.appendChild(queryXML.createTextNode(extensionId));
    rootElement.appendChild(el);
    el = queryXML.createElement("share-version");
    el.appendChild(queryXML.createTextNode(shareVersion));
    rootElement.appendChild(el);
    el = queryXML.createElement("repo-version");
    el.appendChild(queryXML.createTextNode(repoVersion));
    rootElement.appendChild(el);
    el = queryXML.createElement("share-id");
    el.appendChild(queryXML.createTextNode(shareId));
    rootElement.appendChild(el);
    el = queryXML.createElement("repo-id");
    el.appendChild(queryXML.createTextNode(repoId));
    rootElement.appendChild(el);
    el = queryXML.createElement("share-files");
    rootElement.appendChild(el);
    for (String fileName : shareHashes.keySet()) {
        Element fileElem = queryXML.createElement("file");
        fileElem.setAttribute("md5hash", shareHashes.get(fileName));
        fileElem.appendChild(queryXML.createTextNode(fileName));
        el.appendChild(fileElem);
    }
    el = queryXML.createElement("repo-files");
    rootElement.appendChild(el);
    for (String fileName : repoHashes.keySet()) {
        Element fileElem = queryXML.createElement("file");
        fileElem.setAttribute("md5hash", repoHashes.get(fileName));
        fileElem.appendChild(queryXML.createTextNode(fileName));
        el.appendChild(fileElem);
    }
    // query server
    try {
        URL url = new URL(
                "https://update.alvexhq.com:443/alfresco/s/api/alvex/extension/" + extensionId + "/update");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        // disable host verification
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.connect();
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        TransformerFactory.newInstance().newTransformer().transform(new DOMSource(queryXML),
                new StreamResult(wr));
        wr.close();
        // get response
        Document responseXML = xmlBuilder.parse(conn.getInputStream());
        XPath xpath = XPathFactory.newInstance().newXPath();

        // get version
        String repoLatestVersion = ((Node) xpath.evaluate("/extension/repo-version/text()", responseXML,
                XPathConstants.NODE)).getNodeValue();
        String shareLatestVersion = ((Node) xpath.evaluate("/extension/share-version/text()", responseXML,
                XPathConstants.NODE)).getNodeValue();
        NodeList nl = (NodeList) xpath.evaluate("/extension/repo-files/file", responseXML,
                XPathConstants.NODESET);
        Map<String, Boolean> repoFiles = new HashMap<String, Boolean>(nl.getLength());
        for (int i = 0; i < nl.getLength(); i++)
            repoFiles.put(nl.item(i).getTextContent(),
                    "ok".equals(nl.item(i).getAttributes().getNamedItem("status").getNodeValue()));
        nl = (NodeList) xpath.evaluate("/extension/share-files/file", responseXML, XPathConstants.NODESET);
        Map<String, Boolean> shareFiles = new HashMap<String, Boolean>(nl.getLength());
        for (int i = 0; i < nl.getLength(); i++)
            shareFiles.put(nl.item(i).getTextContent(),
                    "ok".equals(nl.item(i).getAttributes().getNamedItem("status").getNodeValue()));
        String motd = ((Node) xpath.evaluate("/extension/motd/text()", responseXML, XPathConstants.NODE))
                .getNodeValue();
        return new ExtensionUpdateInfo(extensionId, repoVersion, shareVersion, repoLatestVersion,
                shareLatestVersion, repoFiles, shareFiles, motd);
    } catch (Exception e) {
        return new ExtensionUpdateInfo(extensionId, repoVersion, shareVersion, "", "",
                new HashMap<String, Boolean>(), new HashMap<String, Boolean>(), "");
    }
}

From source file:org.kontalk.client.ClientHTTPConnection.java

private void setupClient(HttpsURLConnection conn, boolean acceptAnyCertificate)
        throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException, NoSuchProviderException, IOException {

    // bug caused by Lighttpd
    //conn.setRequestProperty("Expect", "100-continue");
    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setDoInput(true);
    conn.setSSLSocketFactory(setupSSLSocketFactory(mContext, mPrivateKey, mCertificate, acceptAnyCertificate));
    if (acceptAnyCertificate)
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
}

From source file:tangocard.sdk.service.ServiceProxy.java

/**
 * Post request./*from w  w w  .  j  a  v a  2s.  c  om*/
 *
 * @return true, if successful
 * @throws Exception the exception
 */
protected String postRequest() throws Exception {
    if (null == this._path) {
        throw new TangoCardSdkException("Member variable '_path' is null.");
    }

    String responseJsonEncoded = null;
    URL url = null;
    HttpsURLConnection connection = null;

    try {
        url = new URL(this._path);
    } catch (MalformedURLException e) {
        throw new TangoCardSdkException("MalformedURLException", e);
    }

    if (this.mapRequest()) {
        try {
            // connect to the server over HTTPS and submit the payload
            connection = (HttpsURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-length", String.valueOf(this._str_request_json.length()));
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");

            // open up the output stream of the connection
            DataOutputStream output = new DataOutputStream(connection.getOutputStream());
            output.write(this._str_request_json.getBytes());
        } catch (Exception e) {
            throw new TangoCardSdkException(String.format("Problems executing request: %s: '%s'",
                    e.getClass().toString(), e.getMessage()), e);
        }

        try {
            // now read the input stream until it is closed, line by line adding to the response
            InputStream inputstream = connection.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
            StringBuffer response = new StringBuffer();
            String line = null;
            while ((line = bufferedreader.readLine()) != null) {
                response.append(line);
            }

            responseJsonEncoded = response.toString();
        } catch (Exception e) {
            throw new TangoCardSdkException(String.format("Problems reading response: %s: '%s'",
                    e.getClass().toString(), e.getMessage()), e);
        }
    }

    return responseJsonEncoded;
}

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 {//from   w  w w  .jav a  2s  .  c o m
        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: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 w w  w  .  j  a v  a 2s  .  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.produban.cloudfoundry.bosh.bosh_javaclient.BoshClientImpl.java

/**
 * This method opens a {@link HttpsURLConnection} to the BOSH director using
 * the given path and sets up 'GET' method and authentication.
 *
 * @param path/*from  w  ww .j ava2 s.c  o m*/
 *            the path (starting with '/')
 * @return the {@link HttpsURLConnection} object
 * @throws MalformedURLException
 * @throws IOException
 * @throws ProtocolException
 * @throws UnsupportedEncodingException
 */
private HttpsURLConnection setupHttpsUrlConnection(String path)
        throws MalformedURLException, IOException, ProtocolException, UnsupportedEncodingException {
    URL requestURL = new URL("https://" + this.host + ":" + this.port + path);
    HttpsURLConnection httpsURLConnection = (HttpsURLConnection) requestURL.openConnection();
    httpsURLConnection.setRequestMethod("GET");
    httpsURLConnection.setUseCaches(false);

    String credentials = this.username + ":" + this.password;
    String basicAuthHeaderValue = "Basic " + Base64.encodeBase64String(credentials.getBytes("UTF-8"));
    httpsURLConnection.setRequestProperty("Authorization", basicAuthHeaderValue);
    httpsURLConnection.setDoInput(true);
    return httpsURLConnection;
}

From source file:org.kuali.mobility.push.dao.PushDaoImpl.java

@SuppressWarnings("unchecked")
private boolean sendPushToAndroid(Push push, Device device) {

    try {/*from   w  ww .j av  a2 s.c om*/
        HttpsURLConnection.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
        URL url = new URL("https://android.apis.google.com/c2dm/send");
        HttpsURLConnection request = (HttpsURLConnection) url.openConnection();

        LOG.info("---- Version: " + url.getClass().getPackage().getSpecificationVersion());
        LOG.info("---- Impl:    " + url.getClass().getPackage().getImplementationVersion());
        String handlers = System.getProperty("java.protocol.handler.pkgs");

        LOG.info(handlers);
        request.setDoOutput(true);
        request.setDoInput(true);

        StringBuilder buf = new StringBuilder();
        buf.append("registration_id").append("=").append((URLEncoder.encode(device.getRegId(), "UTF-8")));
        buf.append("&collapse_key").append("=")
                .append((URLEncoder.encode(push.getPostedTimestamp().toString(), "UTF-8")));
        buf.append("&data.message").append("=").append((URLEncoder.encode(push.getMessage(), "UTF-8")));
        buf.append("&data.title").append("=").append((URLEncoder.encode(push.getTitle(), "UTF-8")));
        buf.append("&data.id").append("=").append((URLEncoder.encode(push.getPushId().toString(), "UTF-8")));
        buf.append("&data.url").append("=").append((URLEncoder.encode(push.getUrl().toString(), "UTF-8")));

        String emer = (push.getEmergency()) ? "YES" : "NO";
        buf.append("&data.emer").append("=").append((URLEncoder.encode(emer, "UTF-8")));

        request.setRequestMethod("POST");
        request.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        request.setRequestProperty("Content-Length", buf.toString().getBytes().length + "");
        request.setRequestProperty("Authorization", "GoogleLogin auth=" + GoogleAuthToken);

        LOG.info("SEND Android Buffer: " + buf.toString());

        OutputStreamWriter post = new OutputStreamWriter(request.getOutputStream());
        post.write(buf.toString());
        post.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
        buf = new StringBuilder();
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            buf.append(inputLine);
        }
        post.close();
        in.close();

        LOG.info("response from C2DM server:\n" + buf.toString());

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.carvoyant.modularinput.Program.java

private JSONObject getRefreshToken(EventWriter ew, String clientId, String clientSecret, String refreshToken) {
    JSONObject tokenJson = null;/*from  w w w . j  a v  a2  s.c om*/
    HttpsURLConnection getTokenConnection = null;

    try {
        BufferedReader tokenResponseReader = null;
        URL url = new URL("https://api.carvoyant.com/oauth/token");
        //         URL url = new URL("https://sandbox-api.carvoyant.com/sandbox/oauth/token");
        getTokenConnection = (HttpsURLConnection) url.openConnection();
        getTokenConnection.setReadTimeout(30000);
        getTokenConnection.setConnectTimeout(30000);
        getTokenConnection.setRequestMethod("POST");
        getTokenConnection.setDoInput(true);
        getTokenConnection.setDoOutput(true);

        List<SimpleEntry> getTokenParams = new ArrayList<SimpleEntry>();
        getTokenParams.add(new SimpleEntry("client_id", clientId));
        getTokenParams.add(new SimpleEntry("client_secret", clientSecret));
        getTokenParams.add(new SimpleEntry("grant_type", "refresh_token"));
        getTokenParams.add(new SimpleEntry("refresh_token", refreshToken));

        String userpass = clientId + ":" + clientSecret;
        String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

        getTokenConnection.setRequestProperty("Authorization", basicAuth);

        OutputStream os = getTokenConnection.getOutputStream();
        os.write(getQuery(getTokenParams).getBytes("UTF-8"));
        os.close();

        if (getTokenConnection.getResponseCode() < 400) {
            tokenResponseReader = new BufferedReader(
                    new InputStreamReader(getTokenConnection.getInputStream()));
            String inputLine;
            StringBuffer sb = new StringBuffer();
            while ((inputLine = tokenResponseReader.readLine()) != null) {
                sb.append(inputLine);
            }

            tokenJson = new JSONObject(sb.toString());
            ew.synchronizedLog(EventWriter.INFO, "Refreshed Carvoyant access token.");
        } else {
            tokenResponseReader = new BufferedReader(
                    new InputStreamReader(getTokenConnection.getErrorStream()));
            StringBuffer sb = new StringBuffer();
            String inputLine;
            while ((inputLine = tokenResponseReader.readLine()) != null) {
                sb.append(inputLine);
            }
            ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error. CLIENT_ID:" + clientId
                    + ", REFRESH_TOKEN:" + refreshToken + ",ERROR_MSG: " + sb.toString());
        }

        getTokenConnection.disconnect();
    } catch (MalformedURLException mue) {
        ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error: " + mue.getMessage());
    } catch (IOException ioe) {
        ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error: " + ioe.getMessage());
    } finally {
        if (null != getTokenConnection) {
            getTokenConnection.disconnect();
        }
    }

    return tokenJson;
}