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

/**
 * Saves a file from the given URL using HTTPS to the given filename and returns the file
 * @param link URL to file/*from www .ja va  2 s .  c o  m*/
 * @param fileName Name to save the file
 * @return The file
 * @throws IOException Thrown if any IOException occurs
 */
public static void saveFileFromNetHTTPS(URL link, String fileName) throws IOException {
    HttpsURLConnection con = (HttpsURLConnection) link.openConnection();

    InputStream in = new BufferedInputStream(con.getInputStream());
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    int n = 0;
    while (-1 != (n = in.read(buf))) {
        out.write(buf, 0, n);
    }
    out.close();
    in.close();
    byte[] response = out.toByteArray();

    File f = new File(fileName);
    if (f.getParentFile() != null) {
        if (f.getParentFile().mkdirs()) {
            System.out.println("Created Directory Structure");
        }
    }

    FileOutputStream fos = new FileOutputStream(f);
    fos.write(response);
    fos.close();
}

From source file:Main.java

private static String getData(String target, String method, String token) {
    try {//from ww  w  .jav a  2 s . co m
        URL url = new URL(target);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        if (!TextUtils.isEmpty(token)) {
            conn.setRequestProperty("Authorization", token);
        }

        conn.setRequestMethod(method);
        conn.connect();

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line, data = "";
        while ((line = in.readLine()) != null) {
            data += line;
        }
        in.close();

        return data;
    } catch (IOException ignored) {
        ignored.printStackTrace();
    }

    return null;
}

From source file:Main.java

public static String executePost(String url, String parameters) throws IOException {

    URL request = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) request.openConnection();
    connection.setDoOutput(true);// w  w  w. j  a  v  a2  s  .  c o m
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("User-Agent", "StripeConnectAndroid");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("charset", "utf-8");
    connection.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length));
    connection.setUseCaches(false);

    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes(parameters);
    wr.flush();
    wr.close();

    String response = streamToString(connection.getInputStream());
    connection.disconnect();
    return response;

}

From source file:com.dianping.phoenix.dev.core.tools.generator.stable.GitRepositoryListGenerator.java

private static String curl(String url) throws Exception {
    URL reqUrl = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) reqUrl.openConnection();
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(3000);//from   w w  w . j  a  va2 s.c o m
    System.out.println(url);
    return IOUtils.toString(new InputStreamReader(conn.getInputStream(), "UTF-8"));
}

From source file:com.dianping.phoenix.dev.core.tools.generator.stable.GitRepositoryListGenerator.java

private static int curl_code(String url) throws Exception {
    URL reqUrl = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) reqUrl.openConnection();
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(3000);//ww w. j a v  a2  s  . c o m

    conn.setRequestProperty("Cookie",
            "uid=code51c3bceea328e0.87696853; remember_user_token=BAhbB1sGaXFJIiIkMmEkMTAkQUR2YXNENGNqT2NSaDBvVWRSS2guTwY6BkVU--bd148a50388e51e524e89809afd6d98e69793711; request_method=GET; _gitlab_session=BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJTMzY2U3YzM3YjlhZWQ1ODcwNDljNDA0MjFkOTdjZjA4BjsAVEkiEF9jc3JmX3Rva2VuBjsARkkiMTNqS1V3V2paUCtCWU0rbVZtTUVraFBpTDR3MGFpZ2FtaExXeWphYjJRSVE9BjsARkkiGXdhcmRlbi51c2VyLnVzZXIua2V5BjsAVFsHWwZpcUkiIiQyYSQxMCRBRHZhc0Q0Y2pPY1JoMG9VZFJLaC5PBjsAVA%3D%3D--af5d6859bcba9e86e72ca6c3b2430400db75dcad");
    return conn.getResponseCode();
}

From source file:Main.java

public static void post(String actionUrl, String file) {
    try {//ww w  .j  a v a 2  s .  c  o m
        URL url = new URL(actionUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setRequestMethod("POST");
        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestProperty("Content-Type", "multipart/form-data;boundary=*****");
        DataOutputStream ds = new DataOutputStream(con.getOutputStream());
        FileInputStream fStream = new FileInputStream(file);
        int bufferSize = 1024; // 1MB
        byte[] buffer = new byte[bufferSize];
        int bufferLength = 0;
        int length;
        while ((length = fStream.read(buffer)) != -1) {
            bufferLength = bufferLength + 1;
            ds.write(buffer, 0, length);
        }
        fStream.close();
        ds.flush();
        InputStream is = con.getInputStream();
        int ch;
        StringBuilder b = new StringBuilder();
        while ((ch = is.read()) != -1) {
            b.append((char) ch);
        }
        new String(b.toString().getBytes("ISO-8859-1"), "utf-8");
        ds.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static String get(String url) {
    try {/*from  ww w.j  a va  2 s .  c  o  m*/
        URL u = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) u.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Charset", "UTF-8");
        InputStream is = connection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String response = "";
        String readLine = "";
        while ((readLine = br.readLine()) != null) {
            response += readLine;
        }
        br.close();
        return response;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:InsertClobToMySqlServlet.java

public static String getClobsContentAsString(String urlAsString) throws Exception {
    InputStream content = null;//from w w  w.  j  a va 2  s.  com
    try {
        URL url = new URL(urlAsString);
        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.sagalasan.eveapi.engine.RequestEngine.java

public static byte[] xmlRequest(XmlRequest xmlRequest) {
    try {/*  w w  w. j  a  va2s  .c om*/
        URL url = new URL(xmlRequest.buildUri());
        URLConnection connection = url.openConnection();
        InputStream inputStream = connection.getInputStream();
        return IOUtils.toByteArray(inputStream);
    } catch (IOException e) {
        logger.error(e.getMessage());
    }

    return null;
}

From source file:Main.java

public static String callJsonAPI(String urlString) {
    // Use HttpURLConnection as per Android 6.0 spec, instead of less efficient HttpClient
    HttpURLConnection urlConnection = null;
    StringBuilder jsonResult = new StringBuilder();

    try {/*from ww w.ja va 2s .  c  om*/
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(TIMEOUT_CONNECTION);
        urlConnection.setReadTimeout(TIMEOUT_READ);
        urlConnection.connect();

        int status = urlConnection.getResponseCode();

        switch (status) {
        case 200:
        case 201:
            BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            String line;
            while ((line = br.readLine()) != null) {
                jsonResult.append(line).append("\n");
            }
            br.close();
        }
    } catch (MalformedURLException e) {
        System.err.print(e.getMessage());
        return e.getMessage();
    } catch (IOException e) {
        System.err.print(e.getMessage());
        return e.getMessage();
    } finally {
        if (urlConnection != null) {
            try {
                urlConnection.disconnect();
            } catch (Exception e) {
                System.err.print(e.getMessage());
            }
        }
    }
    return jsonResult.toString();
}