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:AIR.Common.Web.FileFtpHandler.java

public static InputStream openStream(URI requestUri) throws FtpResourceException {
    try {/*from  w w w.jav  a2 s .c o m*/
        URL url = requestUri.toURL();
        URLConnection urlc = url.openConnection();
        return urlc.getInputStream();
    } catch (IOException exp) {
        throw new FtpResourceException(exp);
    }
}

From source file:co.alligo.toasted.routes.Announce.java

public static boolean checkGameServer(String ip, String port) {
    boolean result;
    URL url;
    URLConnection urlConnection;//from  www . ja v a 2s .co m
    DataInputStream dis;

    try {
        url = new URL("http://" + ip + ":" + port + "/");

        urlConnection = url.openConnection();
        urlConnection.connect();

        result = true;
    } catch (IOException ioe) {
        result = false;
    }
    return result;
}

From source file:com.alexoree.jenkins.Main.java

private static String download(String localName, String remoteUrl) throws Exception {
    URL obj = new URL(remoteUrl);
    HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
    conn.setReadTimeout(5000);/* www  .  ja  v  a2 s.  c  o m*/

    System.out.println("Request URL ... " + remoteUrl);

    boolean redirect = false;

    // normally, 3xx is redirect
    int status = conn.getResponseCode();
    if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER)
            redirect = true;
    }

    if (redirect) {

        // get redirect url from "location" header field
        String newUrl = conn.getHeaderField("Location");

        // get the cookie if need, for login
        String cookies = conn.getHeaderField("Set-Cookie");

        // open the new connnection again
        conn = (HttpURLConnection) new URL(newUrl).openConnection();

        String version = newUrl.substring(newUrl.lastIndexOf("/", newUrl.lastIndexOf("/") - 1) + 1,
                newUrl.lastIndexOf("/"));
        String pluginname = localName.substring(localName.lastIndexOf("/") + 1);
        String ext = "";
        if (pluginname.endsWith(".war"))
            ext = ".war";
        else
            ext = ".hpi";

        pluginname = pluginname.replace(ext, "");
        localName = localName.replace(pluginname + ext,
                "/download/plugins/" + pluginname + "/" + version + "/");
        new File(localName).mkdirs();
        localName += pluginname + ext;
        System.out.println("Redirect to URL : " + newUrl);

    }
    if (new File(localName).exists()) {
        System.out.println(localName + " exists, skipping");
        return localName;
    }

    byte[] buffer = new byte[2048];

    FileOutputStream baos = new FileOutputStream(localName);
    InputStream inputStream = conn.getInputStream();
    int totalBytes = 0;
    int read = inputStream.read(buffer);
    while (read > 0) {
        totalBytes += read;
        baos.write(buffer, 0, read);
        read = inputStream.read(buffer);
    }
    System.out.println("Retrieved " + totalBytes + "bytes");

    return localName;

}

From source file:com.att.ads.sample.SpeechAuth.java

/**
 * Sets up an OAuth client credentials authentication.
 * Follow this with a call to fetchTo() to actually load the data.
 * @param oauthService the URL of the OAuth client credentials service
 * @param apiKey the OAuth client ID//from   www  .j  av  a  2s  .  co m
 * @param apiSecret the OAuth client secret
 * @throws IllegalArgumentException for bad URL, etc.
**/
public static SpeechAuth forService(String oauthService, String oauthScope, String apiKey, String apiSecret)
        throws IllegalArgumentException {
    try {
        URL url = new URL(oauthService);
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        String data = String.format(Locale.US, OAUTH_DATA, oauthScope, apiKey, apiSecret);
        byte[] bytes = data.getBytes("UTF8");
        request.setConnectTimeout(CONNECT_TIMEOUT);
        request.setReadTimeout(READ_TIMEOUT);
        return new SpeechAuth(request, bytes);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    } catch (ClassCastException e) {
        throw new IllegalArgumentException("URL must be HTTP: " + oauthService, e);
    }
}

From source file:jp.seikeidenron.androidtv.common.Utils.java

public static JSONObject parseUrl(String urlString) {
    Log.v(TAG, "Parse URL: " + urlString);
    BufferedReader reader = null;

    try {//  ww w .  j a va 2 s .c  o m
        java.net.URL url = new java.net.URL(urlString);
        URLConnection urlConnection = url.openConnection();
        reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        //urlConnection.getInputStream(), "iso-8859-1"));
        return convertBufferedReaderToJSONObject(reader);
    } catch (Exception e) {
        Log.w(TAG, "Failed to parse the json for media list", e);
        return null;
    } finally {
        if (null != reader) {
            try {
                reader.close();
            } catch (IOException e) {
                Log.w(TAG, "JSON feed closed", e);
            }
        }
    }
}

From source file:net.meltdowntech.steamstats.SteamUser.java

public static List<SteamUser> fetchUsers(List<Long> ids) {
    List<SteamUser> users = new ArrayList<>();
    int queries = (int) Math.ceil(ids.size() / 100.0);

    //Query every hundred users
    Util.printDebug("Fetching users");
    Util.printInfo(String.format("%d user%s allotted", ids.size(), ids.size() == 1 ? "" : "s"));
    Util.printDebug(String.format("%d quer%s allotted", queries, queries == 1 ? "y" : "ies"));
    for (int x = 0; x < queries; x++) {
        //Create steam ids query string
        String steamIds = "&steamids=";
        for (int y = x * 100; y < (x + 1) * 100 && y < ids.size(); y++) {
            steamIds += ids.get(y) + ",";
        }/*from   w  ww. java 2  s  . c o m*/

        //Create query url
        String url = Steam.URL + Steam.PLAYER_DATA + "?key=" + Steam.KEY + steamIds;
        try {
            //Attempt connection and parse
            URL steam = new URL(url);
            URLConnection steamConn = steam.openConnection();
            Reader steamReader = new InputStreamReader(steamConn.getInputStream());
            JSONTokener steamTokener = new JSONTokener(steamReader);
            JSONObject data = (JSONObject) steamTokener.nextValue();
            JSONObject response = data.getJSONObject("response");
            JSONArray players = response.getJSONArray("players");

            //Parse each player
            for (int y = 0; y < players.length(); y++) {
                JSONObject player = players.getJSONObject(y);
                SteamUser user = new SteamUser();

                //Parse each field
                Iterator keys = player.keys();
                while (keys.hasNext()) {
                    String key = (String) keys.next();
                    user.values.put(key, player.get(key));
                }
                users.add(user);
            }
        } catch (MalformedURLException ex) {
            Util.printError("Invalid URL");
        } catch (IOException | JSONException ex) {
            Util.printError("Invalid data");
        } catch (Exception ex) {
            Util.printError("Generic error");
        }

    }
    Util.printDebug("Done fetching users");
    return users;
}

From source file:Main.java

/**
 * Downloads a file via HTTP(S) GET to the given path. This function cannot be called from the
 * UI thread. Android does not allow it.
 *
 * @param urlString Url to the ressource to download.
 * @param file      file to be written to.
 * @param overwrite if file exists, overwrite?
 * @return flase if download was not successful. If successful, true.
 *//*from w  ww.  ja v  a2s .co  m*/
private static Boolean fileDownloadHttp(String urlString, File file, Boolean overwrite) {
    HashMap<String, String> result = null;
    URL url = null;
    //        File temp;

    try {
        url = new URL(urlString);

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setReadTimeout(200000);
        urlConnection.connect();
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        FileOutputStream outputStream = new FileOutputStream(file);

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = in.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }

        in.close();
        outputStream.close();
        urlConnection.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    Log.d(TAG, "File download: " + file.getAbsolutePath() + url.getFile() + "overwrite " + overwrite
            + "exists? " + file.exists());
    return true;
}

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

public static String postUrl(String url, Map<String, String> params)
        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();
    String data = "";
    for (String key : params.keySet()) {
        data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(params.get(key), "UTF-8");
    }/*from w w  w.java2 s  .  c  o m*/
    data = data.substring(1);

    System.out.println("postUrl=>data:" + data);
    URL aURL = new java.net.URL(url);
    HttpsURLConnection aConnection = (HttpsURLConnection) aURL.openConnection();
    aConnection.setSSLSocketFactory(ssf);
    aConnection.setDoOutput(true);
    aConnection.setDoInput(true);
    aConnection.setRequestMethod("POST");
    OutputStreamWriter streamToAuthorize = new java.io.OutputStreamWriter(aConnection.getOutputStream());
    streamToAuthorize.write(data);
    streamToAuthorize.flush();
    streamToAuthorize.close();
    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:flexpos.restfulConnection.java

public static String postRESTful(String RESTfull_URL, String data) {
    String state = "";
    try {/*from  w w w.j  av a2s . co m*/
        URL url = new URL(RESTfull_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send request
        postRequest(connection, data);

        //Get Response
        state = postResponse(connection);

        if (connection != null) {
            connection.disconnect();
        }
    } catch (Exception ex) {
        Logger.getLogger(restfulConnection.class.getName()).log(Level.SEVERE, null, ex);
    }

    return state;
}

From source file:com.meetingninja.csse.database.ContactDatabaseAdapter.java

public static List<Contact> deleteContact(String relationID) throws IOException {

    String _url = getBaseUri().appendPath("Relations").appendPath(relationID).build().toString();
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(IRequest.DELETE);

    addRequestHeader(conn, false);/*from   w w  w . ja va  2 s.c om*/
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);

    boolean result = false;
    JsonNode tree = MAPPER.readTree(response);
    if (!response.isEmpty()) {
        if (!tree.has(Keys.DELETED)) {
            result = true;
        } else {
            logError(TAG, tree);
        }
    }

    conn.disconnect();
    SessionManager session = SessionManager.getInstance();
    List<Contact> contacts = getContacts(session.getUserID());
    return contacts;
}