Example usage for java.net HttpURLConnection connect

List of usage examples for java.net HttpURLConnection connect

Introduction

In this page you can find the example usage for java.net HttpURLConnection connect.

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

From source file:io.jari.geenstijl.API.API.java

public static String postUrl(String url, List<NameValuePair> params, String cheader, boolean refererandorigin)
        throws IOException {
    HttpURLConnection http = (HttpURLConnection) new URL(url).openConnection();
    http.setRequestMethod("POST");
    http.setDoInput(true);//from   w ww.  ja va2s . c  o  m
    http.setDoOutput(true);
    if (cheader != null)
        http.setRequestProperty("Cookie", cheader);
    if (refererandorigin) {
        http.setRequestProperty("Referer",
                "http://www.geenstijl.nl/mt/archieven/2014/01/brein_chanteert_ondertitelaars.html");
        http.setRequestProperty("Origin", "http://www.geenstijl.nl");
    }
    OutputStream os = http.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(getQuery(params));
    writer.flush();
    writer.close();
    os.close();

    http.connect();

    InputStream in = http.getInputStream();
    String encoding = http.getContentEncoding();
    encoding = encoding == null ? "UTF-8" : encoding;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[8192];
    int len = 0;
    while ((len = in.read(buf)) != -1) {
        baos.write(buf, 0, len);
    }
    return new String(baos.toByteArray(), encoding);
}

From source file:edu.rit.chrisbitler.ritcraft.slackintegration.SlackIntegration.java

private void startRTM() throws IOException, URISyntaxException, DeploymentException {
    URL url = new URL("https://www.slack.com/api/rtm.start?token=" + BOT_TOKEN);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setInstanceFollowRedirects(true);
    conn.connect();
    JSONObject returnVal = (JSONObject) JSONValue.parse(new InputStreamReader((InputStream) conn.getContent()));
    String wsUrl = (String) returnVal.get("url");

    //unescape the wsUrl string's slashes
    wsUrl = wsUrl.replace("\\", "");

    //Query the users so we can link user id -> username
    System.out.println("Querying slack users..");
    UserList.queryUsers();//from w ww .  j av  a 2s .c  o m

    System.out.println("Recieved WebSocket URI from slack, connecting... " + wsUrl);

    //Connect via the real-time messaging client and the websocket.
    ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();
    client = ClientManager.createClient();
    rtm = new RTMClient();
    client.connectToServer(rtm, cec, new URI(wsUrl));
}

From source file:weavebytes.com.futureerp.activities.DashBoardActivity.java

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        try {/*from   w ww  .  ja v a2  s .  c  o m*/
            URL url = new URL("http://www.google.com");
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(2000);
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return new Boolean(true);
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:com.juick.android.Utils.java

public static Bitmap downloadImage(String url) {
    try {//from w  w w.ja v  a 2s.c o  m
        URL imgURL = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) imgURL.openConnection();
        conn.setDoInput(true);
        conn.connect();
        return BitmapFactory.decodeStream(conn.getInputStream());
    } catch (Exception e) {
        Log.e("downloadImage", e.toString());
    }
    return null;
}

From source file:eu.peppol.smp.SmpContentRetrieverImpl.java

/**
 * Gets the XML content of a given url, wrapped in an InputSource object.
 *///from   w  w w . j av a 2 s  . com
@Override
public InputSource getUrlContent(URL url) {

    HttpURLConnection httpURLConnection = null;
    try {
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.connect();
    } catch (IOException e) {
        throw new IllegalStateException("Unable to connect to " + url + " ; " + e.getMessage(), e);
    }

    try {
        if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_UNAVAILABLE)
            throw new TryAgainLaterException(url, httpURLConnection.getHeaderField("Retry-After"));
        if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK)
            throw new ConnectionException(url, httpURLConnection.getResponseCode());
    } catch (IOException e) {
        throw new RuntimeException("Problem reading URL data at " + url.toExternalForm(), e);
    }

    try {

        String encoding = httpURLConnection.getContentEncoding();
        InputStream in = new BOMInputStream(httpURLConnection.getInputStream());
        InputStream result;

        if (encoding != null && encoding.equalsIgnoreCase(ENCODING_GZIP)) {
            result = new GZIPInputStream(in);
        } else if (encoding != null && encoding.equalsIgnoreCase(ENCODING_DEFLATE)) {
            result = new InflaterInputStream(in);
        } else {
            result = in;
        }

        String xml = readInputStreamIntoString(result);

        return new InputSource(new StringReader(xml));

    } catch (Exception e) {
        throw new RuntimeException("Problem reading URL data at " + url.toExternalForm(), e);
    }

}

From source file:net.ae97.pokebot.extensions.scrolls.BadgeRanks.java

private synchronized void sync() {
    if (lastUpdate + (1000 * 60 * 60 * 24) > System.currentTimeMillis()) {
        return;/*  w w  w  .  j a v a  2 s  . com*/
    }
    try {
        URL url = new URL(syncURL);
        List<String> lines = new LinkedList<>();
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("User-Agent", "PokeBot - " + PokeBot.VERSION);
        conn.connect();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        }
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(StringUtils.join(lines, "\n"));
        JsonObject obj = element.getAsJsonObject();

        String result = obj.get("msg").getAsString();
        if (!result.equalsIgnoreCase("success")) {
            throw new IOException("API replied with error");
        }

        JsonArray dataObject = obj.get("data").getAsJsonArray();
        synchronized (ranks) {
            ranks.clear();
            for (int i = 0; i < dataObject.size(); i++) {
                JsonObject rank = dataObject.get(i).getAsJsonObject();
                ranks.put(rank.get("id").getAsString(), rank.get("name").getAsString());
            }
            ranks.put("-1", "No badge");
        }
        lastUpdate = System.currentTimeMillis();
    } catch (IOException | JsonSyntaxException ex) {
        extension.getLogger().log(Level.SEVERE, "Error on syncing badge ranks", ex);
        lastUpdate = -1;
    }
}

From source file:MyWeatherService.java

String getWeatherFromInternet(String location) {
    String temperature = "", condition = "", weatherString;

    URL url;//from  www  .j  a va2s .  c  om

    if (location != null && !location.equals("")) {
        try {
            url = new URL(WEATHER_UNDERGROUND_URL + location + ".json");

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();

            InputStream input = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));

            String oneLineFromInternet;
            String wholeReplyFromInternet = "";
            while ((oneLineFromInternet = reader.readLine()) != null) {
                wholeReplyFromInternet += oneLineFromInternet + " ";
            }

            JSONObject jsonObject = new JSONObject(wholeReplyFromInternet);
            JSONObject current_observation = jsonObject.getJSONObject("current_observation");
            temperature = current_observation.getString(TEMP_F);
            condition = current_observation.getString(CONDITION);

        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }

        weatherString = temperature + (char) 0x00B0 + "F " + condition;
    } else {
        weatherString = "It's dark at night.";
    }
    return weatherString;
}

From source file:it.openyoureyes.test.panoramio.Panoramio.java

private Bitmap downloadFile(String url) {
    Bitmap bmImg = null;/*from w w  w. j  av a 2  s . c  om*/
    URL myFileUrl = null;
    if (Util.isEmpty(url))
        return null;
    try {
        myFileUrl = new URL(url);
    } catch (MalformedURLException e) {

        e.printStackTrace();
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();
        // BitmapFactory.Options op=new BitmapFactory.Options();
        // op.inSampleSize = 3;
        bmImg = BitmapFactory.decodeStream(is);// ,null,op);
        conn.disconnect();

    } catch (IOException e) {

        e.printStackTrace();
    }
    return bmImg;
}

From source file:com.juick.android.Utils.java

public static int doHttpGetRequest(String url) {
    try {/*  w  w w . j a v  a 2s . co  m*/
        HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection();
        conn.setUseCaches(false);
        conn.connect();
        int status = conn.getResponseCode();
        conn.disconnect();
        return status;
    } catch (Exception e) {
        Log.e("doHttpGetRequest", e.toString());
    }
    return 0;
}

From source file:libraryjava.parseJSON.java

/**
 * Bitmap//from  www. j  a v  a 2 s .c  o m
 * @param urll
 * @return Bitmap
 */
public Bitmap doInBackground(String urll) {
    StrictMode();

    try {

        URL url = new URL(urll);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();

        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);

        return myBitmap;

    } catch (Exception ex) {
        return null;
    }
}