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:org.cytoscape.app.internal.net.server.AddAccessControlAllowOriginHeaderAfterResponseTest.java

private static HttpURLConnection connectToURL(String urlString, String method) throws Exception {
    final URL url = new URL(urlString);
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(method);
    connection.setDoOutput(true);/* w  ww .j av  a 2 s .co  m*/
    connection.setConnectTimeout(1000);
    connection.connect();
    return connection;
}

From source file:com.abid_mujtaba.bitcoin.tracker.network.Client.java

private static String get(String url_string) throws ClientException {
    HttpURLConnection connection = null; // NOTE: fetchImage is set up to use HTTP not HTTPS

    try {//from   w  w  w . jav  a 2 s  .  com
        URL url = new URL(url_string);
        connection = (HttpURLConnection) url.openConnection();

        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);

        InputStream is = new BufferedInputStream(connection.getInputStream());

        int response_code;

        if ((response_code = connection.getResponseCode()) != 200) {
            throw new ClientException("Error code returned by response: " + response_code);
        }

        return InputStreamToString(is);
    } catch (SocketTimeoutException e) {
        throw new ClientException("Socket timed out.", e);
    } catch (IOException e) {
        throw new ClientException("IO Exception raised while attempting to GET response.", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.krawler.esp.utils.HttpPost.java

public static String GetResponse(String postdata) {
    try {/*from  ww w . j a  v a 2  s.  co  m*/
        String s = URLEncoder.encode(postdata, "UTF-8");
        // URL u = new URL("http://google.com");
        URL u = new URL("http://localhost:7070/service/soap/");
        URLConnection uc = u.openConnection();
        uc.setDoOutput(true);
        uc.setDoInput(true);
        uc.setAllowUserInteraction(false);

        DataOutputStream dstream = new DataOutputStream(uc.getOutputStream());

        // The POST line
        dstream.writeBytes(s);
        dstream.close();

        // Read Response
        InputStream in = uc.getInputStream();
        int x;
        while ((x = in.read()) != -1) {
            System.out.write(x);
        }
        in.close();

        BufferedReader r = new BufferedReader(new InputStreamReader(in));
        StringBuffer buf = new StringBuffer();
        String line;
        while ((line = r.readLine()) != null) {
            buf.append(line);
        }
        return buf.toString();
    } catch (Exception e) {
        // throw e;
        return e.toString();
    }
}

From source file:Main.java

/**
 *  This method is used to send a XML request file to web server to process the request and return
 *  xml response containing event id./*  www .  jav a2 s . c o m*/
 */
public static String postXMLWithTimeout(String postUrl, String xml, int readTimeout) throws Exception {

    System.out.println("XMLUtils.postXMLWithTimeout: Connecting to Web Server .......");

    InputStream in = null;
    BufferedReader bufferedReader = null;
    OutputStream out = null;
    PrintWriter printWriter = null;
    StringBuffer responseMessageBuffer = new StringBuffer("");

    try {
        URL url = new URL(postUrl);
        URLConnection con = url.openConnection();

        // Prepare for both input and output
        con.setDoInput(true);
        con.setDoOutput(true);

        // Turn off caching
        con.setUseCaches(false);
        con.setRequestProperty("Content-Type", "text/xml");
        con.setReadTimeout(readTimeout);
        out = con.getOutputStream();
        // Write the arguments as post data
        printWriter = new PrintWriter(out);

        printWriter.println(xml);
        printWriter.flush();

        //Process response and return back to caller function
        in = con.getInputStream();
        bufferedReader = new BufferedReader(new InputStreamReader(in));
        String tempStr = null;

        int tempClearResponseMessageBufferCounter = 0;
        while ((tempStr = bufferedReader.readLine()) != null) {
            tempClearResponseMessageBufferCounter++;
            //clear the buffer for the first time
            if (tempClearResponseMessageBufferCounter == 1)
                responseMessageBuffer.setLength(0);
            responseMessageBuffer.append(tempStr);
        }

    } catch (Exception ex) {
        throw ex;
    } finally {
        System.out.println("Calling finally in POSTXML");
        try {
            if (in != null)
                in.close();
        } catch (Exception eex) {
            System.out.println("COULD NOT Close Input Stream in try");
        }
        try {
            if (out != null)
                out.close();
        } catch (Exception eex) {
            System.out.println("COULD NOT Close Output Stream in try");
        }

    }
    System.out.println("XMLUtils.postXMLWithTimeout: end .......");
    return responseMessageBuffer.toString();
}

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

public static SteamGame fetchGame(int id) {
    //Create query url
    String url = Steam.URL + Steam.GAME_DATA + "?key=" + Steam.KEY + "&appid=" + id;
    try {/*from   w w w.  jav  a 2 s.  c om*/
        //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("game");
        SteamGame game = new SteamGame();

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

From source file:Main.java

public static String customrequestget(String url, HashMap<String, String> map, String method) {

    if (null != map) {
        int i = 0;
        for (Map.Entry<String, String> entry : map.entrySet()) {

            if (i == 0) {
                url = url + "?" + entry.getKey() + "=" + entry.getValue();
            } else {
                url = url + "&" + entry.getKey() + "=" + entry.getValue();
            }/*www  . j a v  a  2 s .  com*/

            i++;
        }
    }
    try {

        URL murl = new URL(url);
        System.out.print(url);
        HttpURLConnection conn = (HttpURLConnection) murl.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod(method);

        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");

        InputStream inStream = conn.getInputStream();
        String result = inputStream2String(inStream);
        conn.disconnect();
        return result;
    } catch (Exception e) {
        // TODO: handle exception
    }
    return null;
}

From source file:Main.java

public static String upLoad(File file, String RequestURL) {
    String BOUNDER = UUID.randomUUID().toString();
    String PREFIX = "--";
    String END = "/r/n";

    try {/* ww  w .  ja  v a  2 s .c o  m*/
        URL url = new URL(RequestURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(TIME_OUT);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Charset", CHARSET);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cotent-Type", CONTENT_TYPE + ";boundary=" + BOUNDER);

        if (file != null) {
            OutputStream outputStream = connection.getOutputStream();

            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDER + END);
            dataOutputStream.write(sb.toString().getBytes());
            InputStream in = new FileInputStream(file);
            byte[] b = new byte[1024];
            int l = 0;
            while ((l = in.read()) != -1) {
                outputStream.write(b, 0, l);
            }
            in.close();
            dataOutputStream.write(END.getBytes());
            dataOutputStream.write((PREFIX + BOUNDER + PREFIX + END).getBytes());
            dataOutputStream.flush();

            int i = connection.getResponseCode();
            if (i == 200) {
                return SUCCESS;
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    return FALIURE;

}

From source file:net.ftb.data.news.RSSReader.java

public static List<NewsArticle> readRSS() {
    try {//from w w w.  j  av  a  2  s  . co  m
        List<NewsArticle> news = Lists.newArrayList();

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        URL u = new URL(Locations.feedURL);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.connect();
        if (conn.getResponseCode() != 200) {
            Logger.logWarn("News download failed");
            AppUtils.debugConnection(conn);
            conn.disconnect();
            return null;
        }
        Document doc = builder.parse(conn.getInputStream());
        NodeList nodes = doc.getElementsByTagName("item");

        for (int i = 0; i < nodes.getLength(); i++) {
            Element element = (Element) nodes.item(i);
            NewsArticle article = new NewsArticle();
            article.setTitle(getTextValue(element, "title"));
            article.setHyperlink(getTextValue(element, "link"));
            article.setBody(getTextValue(element, "content:encoded"));
            article.setDate(getTextValue(element, "pubDate"));
            news.add(article);
        }

        return news;
    } catch (Exception ex) {
        Logger.logWarn("News download failed", ex);
        return null;
    }
}

From source file:UrlHelper.java

public static void downloadFile(String adresse, File dest) {
    BufferedReader reader = null;
    FileOutputStream fos = null;// ww w  .j a va2  s  . c o  m
    InputStream in = null;
    try {

        // cration de la connection
        URL url = new URL(adresse);
        URLConnection conn = url.openConnection();
        String FileType = conn.getContentType();

        int FileLenght = conn.getContentLength();
        if (FileLenght == -1) {
            throw new IOException("Fichier non valide.");
        }

        // lecture de la rponse
        in = conn.getInputStream();
        reader = new BufferedReader(new InputStreamReader(in));
        if (dest == null) {
            String FileName = url.getFile();
            FileName = FileName.substring(FileName.lastIndexOf('/') + 1);
            dest = new File(FileName);
        }
        fos = new FileOutputStream(dest);
        byte[] buff = new byte[1024];
        int l = in.read(buff);
        while (l > 0) {
            fos.write(buff, 0, l);
            l = in.read(buff);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.vaadin.tools.ReportUsage.java

private static void doHttpGet(String userAgent, String url) {
    Throwable caught;//from  www. j a  v a 2  s. co m
    InputStream is = null;
    try {
        URL urlToGet = new URL(url);
        URLConnection conn = urlToGet.openConnection();
        conn.setRequestProperty(USER_AGENT, userAgent);
        is = conn.getInputStream();
        // TODO use the results
        IOUtils.toByteArray(is);
        return;
    } catch (MalformedURLException e) {
        caught = e;
    } catch (IOException e) {
        caught = e;
    } finally {
        IOUtils.closeQuietly(is);
    }

    Logger.getLogger(ReportUsage.class.getName())
            .fine("Caught an exception while executing HTTP query: " + caught.getMessage());
}