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:com.adobe.ibm.watson.traits.impl.WatsonServiceClient.java

/**
 * Fetches the IBM Watson Personal Insights report using the user's Twitter Timeline.
 * @param language/*from www.jav  a2s. com*/
 * @param tweets
 * @param resource
 * @return
 * @throws Exception
 */
public String getWatsonScore(String language, String tweets, Resource resource) throws Exception {

    HttpsURLConnection connection = null;

    // Check if the username and password have been injected to the service.
    // If not, extract them from the cloud service configuration attached to the page.
    if (this.username == null || this.password == null) {
        getWatsonCloudSettings(resource);
    }

    // Build the request to IBM Watson.
    log.info("The Base Url is: " + this.baseUrl);
    String encodedCreds = getBasicAuthenticationEncoding();
    URL url = new URL(this.baseUrl + "/v2/profile");

    connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Content-Language", language);
    connection.setRequestProperty("Accept-Language", "en-us");
    connection.setRequestProperty("Content-Type", ContentType.TEXT_PLAIN.toString());
    connection.setRequestProperty("Authorization", "Basic " + encodedCreds);
    connection.setUseCaches(false);
    connection.getOutputStream().write(tweets.getBytes());
    connection.getOutputStream().flush();
    connection.connect();

    log.info("Parsing response from Watson");
    StringBuilder str = new StringBuilder();

    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line = "";
    while ((line = br.readLine()) != null) {
        str.append(line + System.getProperty("line.separator"));
    }

    if (connection.getResponseCode() != 200) {
        // The call failed, throw an exception.
        log.error(connection.getResponseCode() + " : " + connection.getResponseMessage());
        connection.disconnect();
        throw new Exception("IBM Watson Server responded with an error: " + connection.getResponseMessage());
    } else {
        connection.disconnect();
        return str.toString();
    }
}

From source file:org.wso2.carbon.identity.authenticator.wikid.WiKIDAuthenticator.java

/**
 * Send REST call//from  ww  w.j av  a 2s.c  o m
 */
private String sendRESTCall(String url, String urlParameters, String formParameters, String httpMethod) {
    String line;
    StringBuilder responseString = new StringBuilder();
    HttpsURLConnection connection = null;
    try {
        setHttpsClientCert(
                "/media/sf_SharedFoldersToVBox/is-connectors/wikid/wikid-authenticator/org.wso2.carbon.identity.authenticator/src/main/resources/localhostWiKID",
                "shakila");
        SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();

        URL wikidEP = new URL(url + urlParameters);
        connection = (HttpsURLConnection) wikidEP.openConnection();
        connection.setSSLSocketFactory(sslsocketfactory);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod(httpMethod);
        connection.setRequestProperty(WiKIDAuthenticatorConstants.HTTP_CONTENT_TYPE,
                WiKIDAuthenticatorConstants.HTTP_CONTENT_TYPE_XWFUE);
        if (httpMethod.toUpperCase().equals(WiKIDAuthenticatorConstants.HTTP_POST)) {
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(),
                    WiKIDAuthenticatorConstants.CHARSET);
            writer.write(formParameters);
            writer.close();
        }
        if (connection.getResponseCode() == 200) {
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = br.readLine()) != null) {
                responseString.append(line);
            }
            br.close();
        } else {
            return WiKIDAuthenticatorConstants.FAILED + WiKIDAuthenticatorConstants.REQUEST_FAILED;
        }
    } catch (ProtocolException e) {
        if (log.isDebugEnabled()) {
            log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage());
        }
        return WiKIDAuthenticatorConstants.FAILED + e.getMessage();
    } catch (MalformedURLException e) {
        if (log.isDebugEnabled()) {
            log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage());
        }
        return WiKIDAuthenticatorConstants.FAILED + e.getMessage();
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage());
        }
        return WiKIDAuthenticatorConstants.FAILED + e.getMessage();
    } finally {
        connection.disconnect();
    }
    return responseString.toString();
}

From source file:org.kontalk.upload.HTPPFileUploadConnection.java

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

    conn.setSSLSocketFactory(//from ww  w.jav  a2s  .c  o  m
            ClientHTTPConnection.setupSSLSocketFactory(mContext, null, null, acceptAnyCertificate));
    if (acceptAnyCertificate)
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
    conn.setRequestProperty("Content-Type", mime != null ? mime : "application/octet-stream");
    // bug caused by Lighttpd
    //conn.setRequestProperty("Expect", "100-continue");

    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestProperty("Content-Length", String.valueOf(length));
    conn.setRequestMethod("PUT");
}

From source file:org.aankor.animenforadio.api.WebsiteGate.java

private JSONObject request(EnumSet<Subscription> subscriptions) throws IOException, JSONException {
    // fetchCookies();

    // TODO: fetch peice by piece
    URL url = new URL("https://www.animenfo.com/radio/index.php?t=" + (new Date()).getTime());
    // URL url = new URL("http://192.168.0.2:12345/");
    String body = "{\"ajaxcombine\":true,\"pages\":[{\"uid\":\"nowplaying\",\"page\":\"nowplaying.php\",\"args\":{\"mod\":\"playing\"}}"
            + ",{\"uid\":\"queue\",\"page\":\"nowplaying.php\",\"args\":{\"mod\":\"queue\"}},{\"uid\":\"recent\",\"page\":\"nowplaying.php\",\"args\":{\"mod\":\"recent\"}}]}";
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Accept", "application/json");
    con.setRequestProperty("Accept-Encoding", "gzip, deflate");
    con.setRequestProperty("Content-Type", "application/json");
    if (!phpSessID.equals(""))
        con.setRequestProperty("Cookie", "PHPSESSID=" + phpSessID);
    con.setRequestProperty("Host", "www.animenfo.com");
    con.setRequestProperty("Referer", "https://www.animenfo.com/radio/nowplaying.php");
    con.setRequestProperty("User-Agent",
            "Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.1.0");
    // con.setUseCaches (false);
    con.setDoInput(true);
    con.setDoOutput(true);//  w w w .  j  ava  2s. c  om

    //Send request

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(body);
    wr.flush();
    wr.close();
    InputStream is = con.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    String line;
    StringBuilder response = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        response.append(line);
    }
    rd.close();

    // updateCookies(con);
    return new JSONObject(response.toString());

}

From source file:ovh.tgrhavoc.aibot.auth.YggdrasilAuthService.java

private JSONObject post(String targetURL, JSONObject request, ProxyData proxy) throws IOException {
    Proxy wrappedProxy = wrapProxy(proxy);
    String requestValue = request.toJSONString();
    HttpsURLConnection connection = null;
    try {//from   ww  w.j  av a  2  s .c o  m
        URL url = new URL(targetURL);
        if (wrappedProxy != null)
            connection = (HttpsURLConnection) url.openConnection(wrappedProxy);
        else
            connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        connection.setRequestProperty("Content-Length", Integer.toString(requestValue.length()));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setReadTimeout(3000);
        connection.setConnectTimeout(3000);

        connection.connect();

        /*Certificate[] certs = connection.getServerCertificates();
                
        byte[] bytes = new byte[294];
        DataInputStream dis = new DataInputStream(Session.class.getResourceAsStream("/minecraft.key"));
        dis.readFully(bytes);
        dis.close();
                
        Certificate c = certs[0];
        PublicKey pk = c.getPublicKey();
        byte[] data = pk.getEncoded();
                
        for(int i = 0; i < data.length; i++)
           if(data[i] != bytes[i])
              throw new RuntimeException("Public key mismatch");*/

        try (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) {
            out.writeBytes(requestValue);
            out.flush();
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            StringBuffer response = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                if (response.length() > 0)
                    response.append('\n');
                response.append(line);
            }
            if (response.toString().trim().isEmpty())
                return null;
            try {
                JSONParser parser = new JSONParser();
                Object responseObject = parser.parse(response.toString());
                if (!(responseObject instanceof JSONObject))
                    throw new IOException("Response not type of JSONObject: " + response);
                return (JSONObject) responseObject;
            } catch (ParseException exception) {
                throw new IOException("Response not valid JSON: " + response, exception);
            }
        }
    } catch (IOException exception) {
        throw exception;
    } catch (Exception exception) {
        throw new IOException("Error connecting", exception);
    } finally {
        if (connection != null)
            connection.disconnect();
    }
}

From source file:com.example.android.networkconnect.MainActivity.java

private String https_token(String urlString) throws IOException {

    String token = null;//from   w w w.  j  a va  2 s . c o  m
    URL url = new URL(urlString);

    if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setChunkedStreamingMode(0);

        conn.setRequestProperty("User-Agent", "e-venement-app/");

        List<String> cookies1 = conn.getHeaderFields().get("Set-Cookie");

        for (int g = 0; g < cookies1.size(); g++) {
            Log.i(TAG, "Cookie_list: " + cookies1.get(g).toString());
            Cookie cookie;
            String[] cook = cookies1.get(g).toString().split(";");

            String[] subcook = cook[0].split("=");
            token = subcook[1];
            Log.i(TAG, "Sub Cook: " + subcook[1]);

            // subcook[1];
        }
    }
    //conn.disconnect();
    return token;
}

From source file:org.kontalk.upload.KontalkBoxUploadConnection.java

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

    conn.setSSLSocketFactory(ClientHTTPConnection.setupSSLSocketFactory(mContext, mPrivateKey, mCertificate,
            acceptAnyCertificate));//from   w w w .  j  a  v  a 2  s.c  o m
    if (acceptAnyCertificate)
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
    conn.setRequestProperty("Content-Type", mime != null ? mime : "application/octet-stream");
    if (encrypted)
        conn.setRequestProperty(HEADER_MESSAGE_FLAGS, "encrypted");
    // bug caused by Lighttpd
    conn.setRequestProperty("Expect", "100-continue");

    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
}

From source file:com.example.android.networkconnect.MainActivity.java

private String https_test(String urlString) throws IOException {

    String token = "";
    URL url = new URL(urlString);

    Log.i(TAG, "Protocol: " + url.getProtocol().toString());

    // if (url.getProtocol().toLowerCase().equals("https")) {
    trustAllHosts();// w w  w  .ja v a 2  s . c  o m

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

    conn.setReadTimeout(20000 /* milliseconds */);
    conn.setConnectTimeout(25000 /* milliseconds */);
    // conn.setRequestMethod("GET");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    conn.setChunkedStreamingMode(0);

    conn.setRequestProperty("User-Agent", "e-venement-app/");

    // OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    //writer.getEncoding();
    //writer.write("&signin[username]=antoine");
    //writer.write("&signin[password]=android2015@");
    //writer.write("?control[id]=");
    //writer.write("&control[ticket_id]=2222");
    //writer.write("&control[checkpoint_id]=1");
    //  writer.write("&control[comment]=");

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //On cre la liste qui contiendra tous nos paramtres

    //Et on y rajoute nos paramtres
    nameValuePairs.add(new BasicNameValuePair("signin[username]", "antoine"));
    nameValuePairs.add(new BasicNameValuePair("signin[password]", "android2015@"));
    //nameValuePairs.add(new BasicNameValuePair("control[id]", ""));
    //nameValuePairs.add(new BasicNameValuePair("control[ticket_id]", "2222"));
    //nameValuePairs.add(new BasicNameValuePair("control[checkpoint_id]", "1"));
    //nameValuePairs.add(new BasicNameValuePair("control[comment]", ""));

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer2.write(getQuery(nameValuePairs));
    writer2.flush();
    //writer2.close();
    //os.close();

    // conn.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    //writer.write("&signin[_csrf_token]="+CSRFTOKEN);
    //writer.flush();

    conn.connect();

    String headerName = null;

    for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
        //data=data+"Header Nme : " + headerName;
        //data=data+conn.getHeaderField(i);
        // Log.i (TAG,headerName);
        Log.i(TAG, headerName + ": " + conn.getHeaderField(i));

    }

    int responseCode = conn.getResponseCode();

    if (responseCode == conn.HTTP_OK) {
        final String COOKIES_HEADER = "Set-Cookie";
        cookie = conn.getHeaderField(COOKIES_HEADER);
    }

    if (conn.getInputStream() != null) {

        // token =getStringFromInputStream(conn.getInputStream());
        Log.i(TAG, readIt(conn.getInputStream(), 15000));
        token = readIt(conn.getInputStream(), 15000);
        Log.i(TAG, getStringFromInputStream(conn.getInputStream()));
        //data=readIt(conn.getInputStream(),7500);
        //Log.i(TAG,token);
        //token=readIt(conn.getInputStream(),7500);
    }
    //conn.connect();
    // List<String> cookiesList = conn.getHeaderFields().get("Set-Cookie");

    // }
    //conn.disconnect();
    return token;
}

From source file:com.dagobert_engine.core.service.MtGoxApiAdapter.java

/**
 * Queries the mtgox api with params/*from  w w  w .  ja va  2 s . c  om*/
 * 
 * @param url
 * @return
 */
public String query(String path, HashMap<String, String> args) {

    final String publicKey = mtGoxConfig.getMtGoxPublicKey();
    final String privateKey = mtGoxConfig.getMtGoxPrivateKey();

    if (publicKey == null || privateKey == null || "".equals(publicKey) || "".equals(privateKey)) {
        throw new ApiKeysNotSetException(
                "Either public or private key of MtGox are not set. Please set them up in src/main/resources/META-INF/seam-beans.xml");
    }

    // Create nonce
    final String nonce = String.valueOf(System.currentTimeMillis()) + "000";

    HttpsURLConnection connection = null;
    String answer = null;
    try {
        // add nonce and build arg list
        args.put(ARG_KEY_NONCE, nonce);
        String post_data = buildQueryString(args);

        String hash_data = path + "\0" + post_data; // Should be correct

        // args signature with apache cryptografic tools
        String signature = signRequest(mtGoxConfig.getMtGoxPrivateKey(), hash_data);

        // build URL
        URL queryUrl = new URL(Constants.API_BASE_URL + path);
        // create and setup a HTTP connection
        connection = (HttpsURLConnection) queryUrl.openConnection();

        connection.setRequestMethod("POST");

        connection.setRequestProperty(REQ_PROP_USER_AGENT, com.dagobert_engine.core.util.Constants.APP_NAME);
        connection.setRequestProperty(REQ_PROP_REST_KEY, mtGoxConfig.getMtGoxPublicKey());
        connection.setRequestProperty(REQ_PROP_REST_SIGN, signature.replaceAll("\n", ""));

        connection.setDoOutput(true);
        connection.setDoInput(true);

        // Read the response

        DataOutputStream os = new DataOutputStream(connection.getOutputStream());
        os.writeBytes(post_data);
        os.close();

        BufferedReader br = null;

        // Any error?
        int code = connection.getResponseCode();
        if (code >= 400) {
            // get error stream
            br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));

            answer = toString(br);
            logger.severe("HTTP Error on queryin " + path + ": " + code + ", answer: " + answer);
            throw new MtGoxConnectionError(code, answer);

        } else {
            // get normal stream
            br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
            answer = toString(br);

        }
    } catch (UnknownHostException exc) {
        throw new MtGoxConnectionError("Could not connect to MtGox. Please check your internet connection. ("
                + exc.getClass().getName() + ")");
    } catch (IllegalStateException ex) {
        throw new MtGoxConnectionError(ex);
    } catch (IOException ex) {
        throw new MtGoxConnectionError(ex);
    } finally {

        if (connection != null)
            connection.disconnect();
        connection = null;
    }

    return answer;
}