Example usage for java.net URL openConnection

List of usage examples for java.net URL openConnection

Introduction

In this page you can find the example usage for java.net URL openConnection.

Prototype

public URLConnection openConnection() throws java.io.IOException 

Source Link

Document

Returns a java.net.URLConnection URLConnection instance that represents a connection to the remote object referred to by the URL .

Usage

From source file:mp3downloader.ZingSearch.java

private static String getDetailResult(String id, String searchType)
        throws UnsupportedEncodingException, MalformedURLException, IOException {
    String data = "{\"id\": \"" + id + "\", \"t\": \"" + searchType + "\"}";
    String jsonData = URLEncoder.encode(Base64.getEncoder().encodeToString(data.getBytes("UTF-8")), "UTF-8");
    String signature = hash_hmac(jsonData, privateKey);
    String urlString = detailUrl + "publicKey=" + publicKey + "&signature=" + signature + "&jsondata="
            + jsonData;//from   w  w  w.jav a  2  s.  c  om
    URL url = new URL(urlString);
    URLConnection urlConn = url.openConnection();
    urlConn.addRequestProperty("User-Agent",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36");
    InputStream is = urlConn.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
    String line;
    StringBuilder sb = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        sb.append(line);
        sb.append("\n");
    }
    is.close();
    String content = sb.toString();
    return content;
}

From source file:org.zywx.wbpalmstar.platform.certificates.Http.java

public static HttpsURLConnection getHttpsURLConnection(URL url) throws Exception {
    HttpsURLConnection mConnection = null;
    mConnection = (HttpsURLConnection) url.openConnection();
    javax.net.ssl.SSLSocketFactory ssFact = null;
    ssFact = Http.getSSLSocketFactory();
    ((HttpsURLConnection) mConnection).setSSLSocketFactory(ssFact);
    if (!isCheckTrustCert()) {
        ((HttpsURLConnection) mConnection).setHostnameVerifier(new HX509HostnameVerifier());
    } else {/*w  w  w .  j av  a 2 s.c o m*/
        ((HttpsURLConnection) mConnection).setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
    }
    return mConnection;
}

From source file:org.apache.nifi.minifi.integration.util.LogUtil.java

public static void verifyLogEntries(String expectedJsonFilename, Container container) throws Exception {
    List<ExpectedLogEntry> expectedLogEntries;
    try (InputStream inputStream = LogUtil.class.getClassLoader().getResourceAsStream(expectedJsonFilename)) {
        List<Map<String, Object>> expected = new ObjectMapper().readValue(inputStream, List.class);
        expectedLogEntries = expected.stream()
                .map(map -> new ExpectedLogEntry(Pattern.compile((String) map.get("pattern")),
                        (int) map.getOrDefault("occurrences", 1)))
                .collect(Collectors.toList());
    }//from   w w  w .j ava  2 s .c  om
    DockerPort dockerPort = container.port(8000);
    URL url = new URL("http://" + dockerPort.getIp() + ":" + dockerPort.getExternalPort());
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try (InputStream inputStream = urlConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
        String line;
        for (ExpectedLogEntry expectedLogEntry : expectedLogEntries) {
            boolean satisfied = false;
            int occurrences = 0;
            while ((line = bufferedReader.readLine()) != null) {
                if (expectedLogEntry.pattern.matcher(line).find()) {
                    logger.info("Found expected: " + line);
                    if (++occurrences >= expectedLogEntry.numOccurrences) {
                        logger.info("Found target " + occurrences + " times");
                        satisfied = true;
                        break;
                    }
                }
            }
            if (!satisfied) {
                fail("End of log reached without " + expectedLogEntry.numOccurrences + " match(es) of "
                        + expectedLogEntry.pattern);
            }
        }
    } finally {
        urlConnection.disconnect();
    }
}

From source file:ro.fortsoft.matilda.util.RecaptchaUtils.java

public static boolean verify(String recaptchaResponse, String secret) {
    if (StringUtils.isNullOrEmpty(recaptchaResponse)) {
        return false;
    }/*w  ww  .ja  v a 2 s .  c o m*/

    boolean result = false;
    try {
        URL url = new URL("https://www.google.com/recaptcha/api/siteverify");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        // add request header
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
        connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String postParams = "secret=" + secret + "&response=" + recaptchaResponse;
        //            log.debug("Post parameters '{}'", postParams);

        // send post request
        connection.setDoOutput(true);
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(postParams);
        outputStream.flush();
        outputStream.close();

        int responseCode = connection.getResponseCode();
        log.debug("Response code '{}'", responseCode);

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();

        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        // print result
        log.debug("Response '{}'", response.toString());

        // parse JSON response and return 'success' value
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(response.toString());
        JsonNode nameNode = rootNode.path("success");

        result = nameNode.asBoolean();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    return result;
}

From source file:com.book.jtm.chap03.HttpClientDemo.java

public static void sendRequest(String method, String url) throws IOException {
    InputStream is = null;/*from  w w w .  j a  va 2 s  . c  o  m*/
    try {
        URL newUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) newUrl.openConnection();
        // ?10
        conn.setReadTimeout(10000);
        // 15
        conn.setConnectTimeout(15000);
        // ?,GET"GET",post"POST"
        conn.setRequestMethod("GET");
        // ??
        conn.setDoInput(true);
        // ??,????
        conn.setDoOutput(true);
        // Header
        conn.setRequestProperty("Connection", "Keep-Alive");
        // ?
        List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
        paramsList.add(new BasicNameValuePair("username", "mr.simple"));
        paramsList.add(new BasicNameValuePair("pwd", "mypwd"));
        writeParams(conn.getOutputStream(), paramsList);

        // ?
        conn.connect();
        is = conn.getInputStream();
        // ?
        String result = convertStreamToString(is);
        Log.i("", "###  : " + result);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.mopaas_mobile.http.BaseHttpRequester.java

public static String doGETwithHeader(String urlstr, String token, List<BasicNameValuePair> params)
        throws IOException {
    String result = null;//from   w ww  .  j  ava  2s .co m
    String content = "";
    for (int i = 0; i < params.size(); i++) {
        content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8") + "="
                + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8");
    }
    URL url = new URL(urlstr + "?" + content.substring(1));
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("token", token);
    connection.setDoInput(true);
    connection.setRequestMethod("GET");
    connection.setUseCaches(false);
    connection.connect();
    InputStream is = connection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

    StringBuffer b = new StringBuffer();
    int ch;
    while ((ch = br.read()) != -1) {
        b.append((char) ch);
    }
    result = b.toString().trim();
    connection.disconnect();
    return result;
}

From source file:com.adguard.compiler.UrlUtils.java

public static String downloadString(URL url, String encoding) throws IOException {

    HttpURLConnection connection = null;
    InputStream inputStream = null;

    try {//www.  j a  v a2s  . c  o m
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        inputStream = connection.getInputStream();
        return IOUtils.toString(inputStream, encoding);
    } finally {
        IOUtils.closeQuietly(inputStream);
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.asual.lesscss.ResourceUtils.java

public static byte[] readTextUrl(URL source, String encoding) throws IOException {
    byte[] result;
    try {//from  w w  w. j a v a  2 s . c o  m
        URLConnection urlc = source.openConnection();
        StringBuffer sb = new StringBuffer(1024);
        InputStream input = urlc.getInputStream();
        UnicodeReader reader = new UnicodeReader(input, encoding);
        try {
            char[] cbuf = new char[32];
            int r;
            while ((r = reader.read(cbuf, 0, 32)) != -1) {
                sb.append(cbuf, 0, r);
            }
            result = sb.toString().getBytes(reader.getEncoding());
        } finally {
            reader.close();
            input.close();
        }
    } catch (IOException e) {
        logger.error("Can't read '" + source.getFile() + "'.");
        throw e;
    }
    return result;
}

From source file:com.ct855.util.HttpsClientUtil.java

public static String getUrl(String url)
        throws IOException, NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {
    //SSLContext??
    TrustManager[] trustAllCerts = new TrustManager[] { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    //SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();

    URL aURL = new java.net.URL(url);
    HttpsURLConnection aConnection = (HttpsURLConnection) aURL.openConnection();
    aConnection.setRequestProperty("Ocp-Apim-Subscription-Key", "d8400b4cdf104015bb23d7fe847352c8");
    aConnection.setSSLSocketFactory(ssf);
    aConnection.setDoOutput(true);// w  w w .  j av  a2s .c om
    aConnection.setDoInput(true);
    aConnection.setRequestMethod("GET");

    InputStream resultStream = aConnection.getInputStream();
    BufferedReader aReader = new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
    StringBuffer aResponse = new StringBuffer();
    String aLine = aReader.readLine();
    while (aLine != null) {
        aResponse.append(aLine + "\n");
        aLine = aReader.readLine();
    }
    resultStream.close();
    return aResponse.toString();
}

From source file:hudson.Main.java

/**
 * Connects to the given HTTP URL and configure time out, to avoid infinite hang.
 *///  ww w .jav a  2s . com
private static HttpURLConnection open(URL url) throws IOException {
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    c.setReadTimeout(TIMEOUT);
    c.setConnectTimeout(TIMEOUT);
    return c;
}