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:com.google.gdocsfs.GoogleDocs.java

public final int getContentLength(URL source) throws IOException {
    HttpURLConnection connection = null;
    try {/*from w  w w .j a v  a  2s. co m*/
        connection = getConnection(source, "HEAD");
        connection.connect();

        { // get content length
            int contentLength = -1;
            String contentLengthStr = connection.getHeaderField("Content-Length");
            if (contentLengthStr != null) {
                try {
                    contentLength = Integer.parseInt(contentLengthStr);
                } catch (NumberFormatException e) {
                    log.warn("Can't parse the content lenght.", e);
                }
            }
            return contentLength;
        }

    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.cloudbees.mtslaves.client.VirtualMachineRef.java

/**
 * Synchronously boot and wait until its fully booted.
 *
 * @return//  w w w .ja  va  2 s.  c o  m
 *      The latest virtual machine state reported by the server when we confirmed a boot.
 */
public VirtualMachine bootSync() throws IOException, InterruptedException {
    HttpURLConnection con = open("boot");
    con.setRequestMethod("POST");
    con.setReadTimeout(BOOT_SYNC_READ_TIMEOUT_MS);
    con.connect();
    drain(con);
    verifyResponseStatus(con);

    for (int i = 0; i < TIMEOUT; i++) {
        Thread.sleep(1000);
        VirtualMachine state = getState();

        if (state.state == null)
            throw new IllegalStateException("Virtual machine failed to boot: " + state.json);

        switch (state.state.getId()) {
        default:
            throw new IllegalStateException(state.state.getId().toString());
        case booting:
            continue; // wait some more
        case running:
            return state;
        case error:
            throw new IllegalStateException("Virtual machine failed to boot: " + state.json);
        }
    }

    throw new IOException("Time out: VM is taking forever to boot" + url);
}

From source file:com.screenslicer.common.CommonUtil.java

public static String post(String uri, String recipient, String postData) {
    HttpURLConnection conn = null;
    try {/*from   w w  w  .  j  a  v a 2  s  .c  o m*/
        postData = Crypto.encode(postData, recipient);
        conn = (HttpURLConnection) new URL(uri).openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(0);
        conn.setRequestProperty("Content-Type", "application/json");
        byte[] bytes = postData.getBytes("utf-8");
        conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
        OutputStream os = conn.getOutputStream();
        os.write(bytes);
        conn.connect();
        if (conn.getResponseCode() == 205) {
            return NOT_BUSY;
        }
        if (conn.getResponseCode() == 423) {
            return BUSY;
        }
        return Crypto.decode(IOUtils.toString(conn.getInputStream(), "utf-8"), recipient);
    } catch (Exception e) {
        Log.exception(e);
    }
    return "";
}

From source file:com.google.gdocsfs.GoogleDocs.java

public final void download(URL source, File target) throws IOException {

    InputStream is = null;/*from  ww  w . j  a  v a2  s  . c o m*/
    FileOutputStream fos = null;
    HttpURLConnection connection = null;

    try {
        connection = getConnection(source, "GET");
        connection.connect();
        is = connection.getInputStream();
        fos = new FileOutputStream(target);
        int readCount;
        byte[] data = new byte[BLOCK_SIZE];
        while ((readCount = is.read(data)) > 0) {
            fos.write(data, 0, readCount);
        }

    } finally {
        if (fos != null) {
            fos.flush();
            fos.close();
        }
        if (is != null) {
            is.close();
        }
        if (connection != null) {
            connection.disconnect();
        }
    }
}

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

@Override
public void runEvent(CommandEvent event) {
    String name = event.getArgs().length > 0 ? event.getArgs()[0] : event.getUser().getNick();
    try {/*from w  w w  .  j  a  va 2 s .c  om*/
        URL playerURL = new URL(url.replace("{name}", name));
        List<String> lines = new LinkedList<>();
        HttpURLConnection conn = (HttpURLConnection) playerURL.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")) {
            event.respond("No data could be retrieved for " + name);
            return;
        }

        JsonObject dataObject = obj.get("data").getAsJsonObject();

        StringBuilder builder = new StringBuilder();

        if (event.getUser().getNick().equalsIgnoreCase(dataObject.get("name").getAsString())) {
            builder.append("Your");
        } else {
            builder.append(dataObject.get("name").getAsString()).append("'s");
        }
        builder.append(" stats - ");
        builder.append("Rating: ").append(dataObject.get("rating").getAsInt()).append(" - ");
        builder.append("Rank: ").append(dataObject.get("rank").getAsInt()).append(" - ");
        builder.append("Badge: ").append(badges.getBadge(dataObject.get("badgerank").getAsString()))
                .append(" - ");
        builder.append("Played: ").append(dataObject.get("played").getAsInt()).append(" - ");
        builder.append("Won: ").append(dataObject.get("won").getAsInt());
        builder.append(" (");
        builder.append(
                (int) ((dataObject.get("won").getAsDouble() / dataObject.get("played").getAsDouble()) * 100));
        builder.append("%) - ");
        builder.append("Judgement wins: ").append(dataObject.get("limitedwon").getAsInt()).append(" - ");
        builder.append("Ranked wins: ").append(dataObject.get("rankedwon").getAsInt()).append(" - ");
        builder.append("Last game played: ").append(parseTime(dataObject.get("lastgame").getAsInt()));

        event.respond(builder.toString());
    } catch (IOException | JsonSyntaxException ex) {
        extension.getLogger().log(Level.SEVERE, "Error on getting player stats for Scrolls for " + name, ex);
        event.respond("Error on getting player stats: " + ex.getLocalizedMessage());
    }
}

From source file:net.sf.taverna.t2.reference.impl.external.http.HttpReference.java

@Override
public Long getApproximateSizeInBytes() {
    long now = currentTimeMillis();
    if (cachedLength != null && cacheTime != null && cacheTime.getTime() + CACHE_TIMEOUT > now)
        return cachedLength;
    try {//from ww  w .  j  a  va2  s  .c  o m
        HttpURLConnection c = (HttpURLConnection) httpUrl.openConnection();
        c.setRequestMethod("HEAD");
        c.connect();
        String lenString = c.getHeaderField("Content-Length");
        if (lenString != null && !lenString.isEmpty()) {
            cachedLength = new Long(lenString);
            cacheTime = new Date(now);
            return cachedLength;
        }
        // there is no Content-Length field so we cannot know the size
    } catch (Exception e) {
        // something went wrong, but we don't care what
    }
    cachedLength = null;
    cacheTime = null;
    return new Long(-1);
}

From source file:com.ngdata.hbaseindexer.util.solr.SolrTestingUtility.java

/**
 * Creates a new core, associated with a collection, in Solr.
 *//*from   w  w w. j a  v  a 2  s .  c o m*/
public void createCore(String coreName, String collectionName, String configName, int numShards, String dataDir)
        throws IOException {
    String url = "http://localhost:" + solrPort + "/solr/admin/cores?action=CREATE&name=" + coreName
            + "&collection=" + collectionName + "&configName=" + configName + "&numShards=" + numShards;

    if (dataDir != null) {
        url += "&dataDir=" + dataDir;
    }

    URL coreActionURL = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) coreActionURL.openConnection();
    conn.connect();
    int response = conn.getResponseCode();
    conn.disconnect();
    if (response != 200) {
        throw new RuntimeException("Request to " + url + ": expected status 200 but got: " + response + ": "
                + conn.getResponseMessage());
    }
}

From source file:org.sample.nonblocking.TestClient.java

/**
 * Processes requests for both HTTP// w ww  . j  a v  a2s. co  m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet TestClient</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet TestClient at " + request.getContextPath() + "</h1>");

        String path = "http://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath() + "/ReadTestServlet";
        out.println("Invoking the endpoint: " + path + "<br>");
        out.flush();
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setChunkedStreamingMode(2);
        conn.setDoOutput(true);
        conn.connect();
        try (BufferedWriter output = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()))) {
            out.println("Sending data ..." + "<br>");
            out.flush();
            output.write("Hello");
            output.flush();
            out.println("Sleeping ..." + "<br>");
            out.flush();
            Thread.sleep(5000);
            out.println("Sending more data ..." + "<br>");
            out.flush();
            output.write("World");
            output.flush();
            output.close();
        }
        out.println("<br><br>Check GlassFish server.log");
        out.println("</body>");
        out.println("</html>");
    } catch (InterruptedException | IOException ex) {
        Logger.getLogger(ReadTestServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Servlet.Cancel.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w  ww . ja v a  2 s.co  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {

        String eventUrl = request.getParameter("eventUrl");
        System.out.print(eventUrl);

        String valid = "valid";

        OAuthConsumer consumer = new DefaultOAuthConsumer("test6-40942", "oQ4q4oBiv9y4jPr7");
        URL url = new URL(eventUrl);
        HttpURLConnection requestUrl = (HttpURLConnection) url.openConnection();
        consumer.sign(requestUrl);
        requestUrl.connect();

        GetResponse gr = new GetResponse();
        gr.validateUrl(valid);

        String result = null;
        StringBuilder sb = new StringBuilder();
        requestUrl.setRequestMethod("GET");
        BufferedReader br = new BufferedReader(new InputStreamReader(requestUrl.getInputStream()));
        String inputLine = "";
        while ((inputLine = br.readLine()) != null) {
            sb.append(inputLine);
        }

        result = sb.toString();

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(result));

        //parsing elements by name tags from event url
        Document doc = builder.parse(src);
        String creatorName = doc.getElementsByTagName("fullName").item(0).getTextContent();
        String companyName = doc.getElementsByTagName("name").item(0).getTextContent();
        String edition = doc.getElementsByTagName("editionCode").item(0).getTextContent();
        String returnUrl = doc.getElementsByTagName("returnUrl").item(0).getTextContent();

        System.out.print(creatorName);
        System.out.print(companyName);
        System.out.print(edition);
        System.out.print(returnUrl);

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost xmlResponse = new HttpPost(returnUrl);
        StringEntity input = new StringEntity(
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><result><success>true</success><message>Account change successful</message>");
        input.setContentType("text/xml");
        xmlResponse.setEntity(input);
        httpClient.execute(xmlResponse);

    } catch (OAuthMessageSignerException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthExpectationFailedException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthCommunicationException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

@Override
public void runEvent(CommandEvent event) {
    if (event.getArgs().length == 0 || (event.getArgs()[0].equals("-d") && event.getArgs().length < 3)) {
        event.respond("Usage: .price <-d days> [name]");
        return;//www  .  jav  a  2 s  . c om
    }
    int days = 2;
    String[] name = event.getArgs();
    if (event.getArgs()[0].equals("-d")) {
        name = new String[event.getArgs().length - 2];
        for (int i = 2; i < event.getArgs().length; i++) {
            name[i - 2] = event.getArgs()[i];
        }
        try {
            days = Integer.parseInt(event.getArgs()[1]);
        } catch (NumberFormatException e) {
            event.respond("Usage: .price <-d days> [name]");
            return;
        }
        if (days > 10 || days < 0) {
            event.respond("The days must be between 1 and 10 (inclusive)");
            return;
        }
    }
    try {
        URL playerURL = new URL(
                url.replace("{days}", Integer.toString(days)).replace("{name}", StringUtils.join(name, "%20")));
        List<String> lines = new LinkedList<>();
        HttpURLConnection conn = (HttpURLConnection) playerURL.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")) {
            event.respond("Scroll not found");
            return;
        }
        JsonObject dataObject = obj.get("data").getAsJsonArray().get(0).getAsJsonObject();

        StringBuilder builder = new StringBuilder();

        builder.append("Buy: ").append(dataObject.get("buy").getAsJsonObject().get("price").getAsInt())
                .append(" Gold - ");
        builder.append("Bought: ").append(dataObject.get("buy").getAsJsonObject().get("pop").getAsInt())
                .append(" - ");
        builder.append("Sell: ").append(dataObject.get("sell").getAsJsonObject().get("price").getAsInt())
                .append(" Gold - ");
        builder.append("Sold: ").append(dataObject.get("sell").getAsJsonObject().get("pop").getAsInt());
        String[] message = builder.toString().split("\n");
        for (String msg : message) {
            event.respond("" + msg);
        }

    } catch (IOException | JsonSyntaxException | IllegalStateException ex) {
        PokeBot.getLogger().log(Level.SEVERE,
                "Error on getting scroll for Scrolls for '" + StringUtils.join(event.getArgs(), " ") + "'", ex);
        event.respond("Error on getting scroll: " + ex.getLocalizedMessage());

    }
}