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:Main.java

private static HttpURLConnection _openPostConnection(String purl) throws IOException {
    URL url = new URL(purl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);/*from   w  ww.  j  a va  2 s  . c  o  m*/
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("User-Agent", "Android Client Agent");

    return connection;
}

From source file:Main.java

static String downloadHtml(String urlString) {
    StringBuffer buffer = new StringBuffer();

    try {/*w ww .j a v a 2 s. c  om*/
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        HttpURLConnection.setFollowRedirects(true);
        conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        String encoding = conn.getContentEncoding();
        InputStream inStr = null;

        if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
            inStr = new GZIPInputStream(conn.getInputStream());
        } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
            inStr = new InflaterInputStream(conn.getInputStream(), new Inflater(true));
        } else {
            inStr = conn.getInputStream();
        }
        int ptr = 0;
        InputStreamReader inStrReader = new InputStreamReader(inStr, Charset.forName("GB2312"));

        while ((ptr = inStrReader.read()) != -1) {
            buffer.append((char) ptr);
        }
        inStrReader.close();
        conn.disconnect();
        inStr.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return buffer.toString();
}

From source file:Main.java

private static HttpURLConnection createHttpsURLConnection(String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(ONE_MINUTE);
    connection.setReadTimeout(ONE_MINUTE);

    return connection;
}

From source file:Main.java

private static String readXmlFromURL(String theUrl) {
    StringBuilder content = new StringBuilder();
    try {/*from w w  w.ja  va2s  . c  om*/
        URL url = new URL(theUrl);
        URLConnection urlConnection = url.openConnection();

        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(urlConnection.getInputStream()));

        String line;
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line + "\n");
        }
        bufferedReader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return content.toString();
}

From source file:com.joliciel.jochre.search.webClient.SearchWebClientUtils.java

public static String getJson(URL url) {
    try {//  w  w w  .  ja v a2s .  c o  m
        URLConnection con = url.openConnection();
        InputStream in = con.getInputStream();
        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String json = writer.toString();
        return json;
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:com.threerings.getdown.util.ConnectionUtil.java

/**
 * Opens a connection to a URL, setting the authentication header if user info is present.
 *///from   w ww .j ava2s. co  m
public static URLConnection open(URL url) throws IOException {
    URLConnection conn = url.openConnection();

    // If URL has a username:password@ before hostname, use HTTP basic auth
    String userInfo = url.getUserInfo();
    if (userInfo != null) {
        // Remove any percent-encoding in the username/password
        userInfo = URLDecoder.decode(userInfo, "UTF-8");
        // Now base64 encode the auth info and make it a single line
        String encoded = Base64.encodeBase64String(userInfo.getBytes("UTF-8")).replaceAll("\\n", "")
                .replaceAll("\\r", "");
        conn.setRequestProperty("Authorization", "Basic " + encoded);
    }

    return conn;
}

From source file:Main.java

public static InputStream getIS(String address) {
    InputStream is = null;//from   w  w w. j a v a2 s. c  o m
    try {
        URL url = new URL(address);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.connect();
        is = conn.getInputStream();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return is;
}

From source file:Main.java

private static String getRawText(String link) throws IOException {

    URL url;
    url = new URL(link);

    URLConnection connection = url.openConnection();

    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(connection.getInputStream(), "UTF-8"));

    StringBuffer stringBuffer = new StringBuffer();
    String inputLine;/*ww w.  jav a2  s  .  c  o m*/
    // read from buffer line by line
    while ((inputLine = bufferedReader.readLine()) != null) {
        stringBuffer.append(inputLine + "\n");
    }
    bufferedReader.close();
    return stringBuffer.toString();
}

From source file:Main.java

/**
 * /*from   w  ww  . j a v a  2  s  .c om*/
 * @param imgURL
 * @return
 */
public static BitmapDrawable downloadBitmapDrawable(String imgURL) {
    BitmapDrawable icon = null;
    try {
        URL url = new URL(imgURL);
        HttpURLConnection hc = (HttpURLConnection) url.openConnection();
        icon = new BitmapDrawable(hc.getInputStream());
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return icon;
}

From source file:MainClass.java

public static void saveBinaryFile(URL u) {
    int bufferLength = 128;
    try {//from   ww  w  .j av  a 2  s.c  o  m
        URLConnection uc = u.openConnection();
        String ct = uc.getContentType();
        int contentLength = uc.getContentLength();
        if (ct.startsWith("text/") || contentLength == -1) {
            System.err.println("This is not a binary file.");
            return;
        }

        InputStream stream = uc.getInputStream();
        byte[] buffer = new byte[contentLength];
        int bytesread = 0;
        int offset = 0;
        while (bytesread >= 0) {
            bytesread = stream.read(buffer, offset, bufferLength);
            if (bytesread == -1)
                break;
            offset += bytesread;
        }
        if (offset != contentLength) {
            System.err.println("Error: Only read " + offset + " bytes");
            System.err.println("Expected " + contentLength + " bytes");
        }

        String theFile = u.getFile();
        theFile = theFile.substring(theFile.lastIndexOf('/') + 1);
        FileOutputStream fout = new FileOutputStream(theFile);
        fout.write(buffer);
    } catch (Exception e) {
        System.err.println(e);
    }
    return;
}