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:it.unicaradio.android.utils.NetworkUtils.java

public static byte[] httpGet(String urlString) throws IOException {
    URL url = new URL(urlString);

    URLConnection ucon = url.openConnection();

    InputStream is = ucon.getInputStream();
    BufferedInputStream bis = new BufferedInputStream(is);

    // Read bytes to the Buffer until there is nothing more to read(-1).
    ByteArrayBuffer baf = new ByteArrayBuffer(50);
    int current = 0;
    while ((current = bis.read()) != -1) {
        baf.append((byte) current);
    }/*from   w  w w  .  j av a2s.com*/

    return baf.toByteArray();
}

From source file:com.kubotaku.android.openweathermap.lib.util.TimeZoneUtil.java

public static TimeZone getTargetTimeZone(LatLng latlng, String apiKey) {
    TimeZone timeZone = null;//  w w w  .  ja  v  a 2 s  . c  o m

    try {
        Date now = new Date();
        long currentTime = now.getTime();
        String requestURL = String.format(API_URL, latlng.latitude, latlng.longitude, currentTime, apiKey);

        URL url = new URL(requestURL);
        InputStream is = url.openConnection().getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line;
        while (null != (line = reader.readLine())) {
            sb.append(line);
        }
        String data = sb.toString();

        timeZone = TimeZoneParser.parseTimeZone(data);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return timeZone;
}

From source file:com.velonuboso.made.core.rat.RatNameHelper.java

public static String getText(URL url) throws Exception {
    URLConnection connection = url.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

    StringBuilder response = new StringBuilder();
    String inputLine;//  ww  w. j  a  v  a  2s.c  o m

    while ((inputLine = in.readLine()) != null)
        response.append(inputLine + "\n");

    in.close();

    return response.toString();
}

From source file:Main.java

@TargetApi(Build.VERSION_CODES.KITKAT)
public static String net(String strUrl, Map<String, Object> params, String method) throws Exception {
    HttpURLConnection conn = null;
    BufferedReader reader = null;
    String rs = null;//from   w w w  .ja va 2  s.c  o  m
    try {
        StringBuffer sb = new StringBuffer();
        if (method == null || method.equals("GET")) {
            strUrl = strUrl + "?" + urlencode(params);
        }
        URL url = new URL(strUrl);
        conn = (HttpURLConnection) url.openConnection();
        if (method == null || method.equals("GET")) {
            conn.setRequestMethod("GET");
        } else {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
        }
        conn.setRequestProperty("User-agent", userAgent);
        conn.setUseCaches(false);
        conn.setConnectTimeout(DEF_CONN_TIMEOUT);
        conn.setReadTimeout(DEF_READ_TIMEOUT);
        conn.setInstanceFollowRedirects(false);
        conn.connect();
        if (params != null && method.equals("POST")) {
            try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
                out.writeBytes(urlencode(params));
            }
        }
        InputStream is = conn.getInputStream();
        reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
        String strRead = null;
        while ((strRead = reader.readLine()) != null) {
            sb.append(strRead);
        }
        rs = sb.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            reader.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }
    return rs;
}

From source file:UpdateMySqlClobServlet.java

public static String getClobsContentAsString(String urlAsString) throws Exception {
    InputStream content = null;/*from   w  w  w  .  j a va 2  s  .c  o m*/
    try {
        java.net.URL url = new java.net.URL(urlAsString);
        java.net.URLConnection urlConn = url.openConnection();
        urlConn.connect();
        content = urlConn.getInputStream();

        int BUFFER_SIZE = 1024;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        int length;
        byte[] buffer = new byte[BUFFER_SIZE];

        while ((length = content.read(buffer)) != -1) {
            output.write(buffer, 0, length);
        }
        return new String(output.toByteArray());

    } finally {
        content.close();
    }
}

From source file:com.athomas.androidkickstartr.util.ResourcesUtils.java

private static void copyResourcesToFromJar(File target, URL url) throws IOException {
    JarURLConnection connection = (JarURLConnection) url.openConnection();
    JarFile jarFile = connection.getJarFile();

    Enumeration<JarEntry> entries = jarFile.entries();

    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        InputStream is = jarFile.getInputStream(jarEntry);
        String entryPath = jarEntry.getName();

        File file = null;/*from ww w . ja va  2s  .  c om*/
        String dirs = "";
        if (entryPath.contains("/")) {
            int lastIndexOf = entryPath.lastIndexOf("/");
            dirs = (String) entryPath.subSequence(0, lastIndexOf + 1);
        }

        File parent = new File(target, dirs);
        parent.mkdirs();

        if (!jarEntry.isDirectory()) {
            String[] splitedPath = entryPath.split("/");
            String fileName = splitedPath[splitedPath.length - 1];
            file = new File(parent, fileName);
            FileUtils.copyInputStreamToFile(is, file);
        }
    }
}

From source file:dk.nsi.minlog.test.utils.TestHelper.java

public static String sendRequest(String url, String action, String docXml, boolean failOnError)
        throws IOException, ServiceException {
    URL u = new URL(url);
    HttpURLConnection uc = (HttpURLConnection) u.openConnection();
    uc.setDoOutput(true);/* ww  w.  ja va 2  s. c  o  m*/
    uc.setDoInput(true);
    uc.setRequestMethod("POST");
    uc.setRequestProperty("SOAPAction", "\"" + action + "\"");
    uc.setRequestProperty("Content-Type", "text/xml; charset=utf-8;");
    OutputStream os = uc.getOutputStream();

    IOUtils.write(docXml, os, "UTF-8");
    os.flush();
    os.close();

    InputStream is;
    if (uc.getResponseCode() != 200) {
        is = uc.getErrorStream();
    } else {
        is = uc.getInputStream();
    }
    String res = IOUtils.toString(is);

    is.close();
    if (uc.getResponseCode() != 200 && (uc.getResponseCode() != 500 || failOnError)) {
        throw new ServiceException(res);
    }
    uc.disconnect();

    return res;
}

From source file:javarestart.JavaRestartLauncher.java

public static String getText(String url) throws IOException {
    URL website = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) website.openConnection();
    try (LineNumberReader in = new LineNumberReader(new InputStreamReader(connection.getInputStream()))) {
        StringBuilder response = new StringBuilder();
        String inputLine;//from w  w w.jav  a2 s  .  com
        while ((inputLine = in.readLine()) != null)
            response.append(inputLine);

        return response.toString();
    }
}

From source file:me.malladi.dashcricket.Util.java

/**
 * Fetch the current live scores./*w  w w  . jav  a  2s.c  o m*/
 * 
 * @return An array of the current live scores.
 */
public static LiveScore[] getLiveScores() {
    try {
        URL url = new URL(LIVE_SCORES_URL);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setUseCaches(false);
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

        StringBuilder json = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            json.append(line);
        }

        JSONArray jsonArray = new JSONArray(json.toString());
        LiveScore[] liveScores = new LiveScore[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); ++i) {
            JSONObject liveScoreJson = (JSONObject) jsonArray.opt(i);
            liveScores[i] = new LiveScore(liveScoreJson);
        }

        return liveScores;
    } catch (Exception e) {
        Log.e(TAG, "exception while fetching live scores", e);
    }
    return null;
}

From source file:com.netsteadfast.greenstep.util.WsServiceUtils.java

public static boolean testConnection(String wsdlAddress) throws Exception {
    if (StringUtils.isBlank(wsdlAddress)) {
        return true;
    }/*from  w  w  w.jav  a2  s  .  c  o  m*/
    boolean status = false;
    try {
        URL url = new URL(wsdlAddress);
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(TIMEOUT);
        connection.setReadTimeout(TIMEOUT);
        if (connection.getContent() != null) {
            status = true;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return status;
}