Example usage for java.net HttpURLConnection getInputStream

List of usage examples for java.net HttpURLConnection getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java

private static String sendGET(URL url, HttpURLConnection con, String userAgent, String tokenId)
        throws IOException {

    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", userAgent);
    con.setRequestProperty("X-Auth-Token", tokenId);

    logger.log(Level.INFO, "Sending GET request to URL : {0}", url);
    int responseCode = con.getResponseCode();
    logger.log(Level.INFO, "Response Code : {0}", responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;/*from  w  ww. j  a  va  2 s . co m*/
    StringBuilder responseStr = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        responseStr.append(inputLine);
    }
    in.close();

    return responseStr.toString();
}

From source file:com.github.terma.m.node.Node.java

private static void send(final String serverHost, final int serverPort, final String context,
        final List<Event> events) throws IOException {
    final HttpURLConnection connection = (HttpURLConnection) new URL("http", serverHost, serverPort,
            context + "/node").openConnection();
    connection.setDoOutput(true);//from w  w  w .  j a  v a 2  s  .  c om
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "text/json");
    connection.setRequestProperty("charset", "utf-8");
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(false);
    connection.connect();
    OutputStream outputStream = connection.getOutputStream();
    outputStream.write(new Gson().toJson(events).getBytes());
    connection.getInputStream().read();
    outputStream.close();
}

From source file:org.apache.felix.http.itest.BaseIntegrationTest.java

protected static void assertContent(int expectedRC, String expected, URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    int rc = conn.getResponseCode();
    assertEquals("Unexpected response code,", expectedRC, rc);

    if (rc >= 200 && rc < 500) {
        InputStream is = null;//from   ww w .  ja  v a2s.  c  o m
        try {
            is = conn.getInputStream();
            assertEquals(expected, slurpAsString(is));
        } finally {
            close(is);
            conn.disconnect();
        }
    } else {
        InputStream is = null;
        try {
            is = conn.getErrorStream();
            assertEquals(expected, slurpAsString(is));
        } finally {
            close(is);
            conn.disconnect();
        }
    }
}

From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java

private static HeliosData loadHelios() throws IOException {
    System.out.println("Finding Helios implementation");

    HeliosData data = new HeliosData();

    boolean needsToDownload = !IMPL_FILE.exists();
    if (!needsToDownload) {
        try (JarFile jarFile = new JarFile(IMPL_FILE)) {
            ZipEntry entry = jarFile.getEntry("META-INF/MANIFEST.MF");
            if (entry == null) {
                needsToDownload = true;//from   w w  w .ja va 2  s. co  m
            } else {
                Manifest manifest = new Manifest(jarFile.getInputStream(entry));
                String ver = manifest.getMainAttributes().getValue("Implementation-Version");
                try {
                    data.buildNumber = Integer.parseInt(ver);
                    data.version = manifest.getMainAttributes().getValue("Version");
                    data.mainClass = manifest.getMainAttributes().getValue("Main-Class");
                } catch (NumberFormatException e) {
                    needsToDownload = true;
                }
            }
        } catch (IOException e) {
            needsToDownload = true;
        }
    }
    if (needsToDownload) {
        URL latestJar = new URL(LATEST_JAR);
        System.out.println("Downloading latest Helios implementation");

        FileOutputStream out = new FileOutputStream(IMPL_FILE);
        HttpURLConnection connection = (HttpURLConnection) latestJar.openConnection();
        if (connection.getResponseCode() == 200) {
            int contentLength = connection.getContentLength();
            if (contentLength > 0) {
                InputStream stream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int amnt;
                AtomicInteger total = new AtomicInteger();
                AtomicBoolean stop = new AtomicBoolean(false);

                Thread progressBar = new Thread() {
                    public void run() {
                        JPanel panel = new JPanel();
                        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

                        JLabel label = new JLabel();
                        label.setText("Downloading latest Helios build");
                        panel.add(label);

                        GridLayout layout = new GridLayout();
                        layout.setColumns(1);
                        layout.setRows(3);
                        panel.setLayout(layout);
                        JProgressBar pbar = new JProgressBar();
                        pbar.setMinimum(0);
                        pbar.setMaximum(100);
                        panel.add(pbar);

                        JTextArea textArea = new JTextArea(1, 3);
                        textArea.setOpaque(false);
                        textArea.setEditable(false);
                        textArea.setText("Downloaded 00.00MB/00.00MB");
                        panel.add(textArea);

                        JFrame frame = new JFrame();
                        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                        frame.setContentPane(panel);
                        frame.pack();
                        frame.setLocationRelativeTo(null);
                        frame.setVisible(true);

                        while (!stop.get()) {
                            SwingUtilities.invokeLater(
                                    () -> pbar.setValue((int) (100.0 * total.get() / contentLength)));

                            textArea.setText("Downloaded " + bytesToMeg(total.get()) + "MB/"
                                    + bytesToMeg(contentLength) + "MB");
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException ignored) {
                            }
                        }
                        frame.dispose();
                    }
                };
                progressBar.start();

                while ((amnt = stream.read(buffer)) != -1) {
                    out.write(buffer, 0, amnt);
                    total.addAndGet(amnt);
                }
                stop.set(true);
                return loadHelios();
            } else {
                throw new IOException("Content-Length set to " + connection.getContentLength());
            }
        } else if (connection.getResponseCode() == 404) { // Most likely bootstrapper is out of date
            throw new RuntimeException("Bootstrapper out of date!");
        } else {
            throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage());
        }
    }

    return data;
}

From source file:mashberry.com500px.util.Api_Parser.java

/*******************************************************************************
  * /*from   w ww.  ja  v a2s  .c o m*/
  *    (  )
  * 
  *******************************************************************************/
public static String get_second_detail(final int position, final String string, final int url_image_size,
        final int comments, final int comments_page) {
    String returnStr = "success";
    String urlStr = DB.Get_Photo_Url + "/" + string + "?image_size=" + url_image_size
    /*+ "&comments="   + comments
    + "&comments_page="   + comments_page*/
            + "&consumer_key=" + Var.consumer_key;
    try {
        URL url = new URL(urlStr);
        URLConnection uc = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) uc;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        httpConn.setConnectTimeout(10000);
        int response = httpConn.getResponseCode();

        if (response == HttpURLConnection.HTTP_OK) {
            InputStream in = httpConn.getInputStream();
            String userPictureOpt = "8";
            String result = convertStreamToString(in);
            JSONObject jObject = new JSONObject(result);
            JSONObject jsonObject = jObject.getJSONObject("photo");

            //            Log.i(TAG, "jsonObject " + jsonObject);

            Var.detail_nameMap.put(position, jsonObject.getString("name"));
            Var.detail_locationMap.put(position, jsonObject.getString("location"));
            Var.detail_ratingMap.put(position, jsonObject.getString("rating"));
            Var.detail_times_viewedMap.put(position, jsonObject.getString("times_viewed"));
            Var.detail_votesMap.put(position, jsonObject.getString("votes_count"));
            Var.detail_favoritesMap.put(position, jsonObject.getString("favorites_count"));
            Var.detail_descriptionMap.put(position, jsonObject.getString("description"));
            Var.detail_cameraMap.put(position, jsonObject.getString("camera"));
            Var.detail_lensMap.put(position, jsonObject.getString("lens"));
            Var.detail_focal_lengthMap.put(position, jsonObject.getString("focal_length"));
            Var.detail_isoMap.put(position, jsonObject.getString("iso"));
            Var.detail_shutter_speedMap.put(position, jsonObject.getString("shutter_speed"));
            Var.detail_apertureMap.put(position, jsonObject.getString("aperture"));
            Var.detail_categoryMap.put(position, jsonObject.getString("category"));
            Var.detail_uploadedMap.put(position, jsonObject.getString("hi_res_uploaded"));
            Var.detail_takenMap.put(position, jsonObject.getString("taken_at"));
            Var.detail_licenseTypeMap.put(position, jsonObject.getString("license_type"));

            JSONObject jsonuser = jsonObject.getJSONObject("user");
            Var.detail_user_nameMap.put(position, jsonuser.getString("fullname"));
            Var.detail_userpicMap.put(position, userPictureOpt + jsonuser.getString("userpic_url"));

            //     ( . .)
            /*JSONArray jsonArray = jObject.getJSONArray("comments");
            for(int i=0 ; i<jsonArray.length() ; i++){
               Var.comment_user_id.add(jsonArray.getJSONObject(i).getString("user_id"));
               Var.comment_body.add(jsonArray.getJSONObject(i).getString("body"));
                       
                JSONObject jsonuser = jsonArray.getJSONObject(i).getJSONObject("user");
                Var.comment_fullname.add(jsonuser.getString("fullname"));
                Var.comment_userpic_url.add(jsonuser.getString("userpic_url"));
            }*/

            /*            Log.i("Main", "feature   " +feature);
                        Log.i("Main", "filters   " +filters);
                        Log.i("Main", "categoryArr   " +Var.categoryArr);
                        Log.i("Main", "idArr   " +Var.idArr);
                        Log.i("Main", "image_urlArr   " +Var.image_urlArr);
                        Log.i("Main", "nameArr   " +Var.nameArr);
                        Log.i("Main", "ratingArr   " +Var.ratingArr);
                        Log.i("Main", "user_firstnameArr   " +Var.user_firstnameArr);
                        Log.i("Main", "user_fullnameArr   " +Var.user_fullnameArr);
                        Log.i("Main", "user_lastnameArr   " +Var.user_lastnameArr);
                        Log.i("Main", "user_upgrade_statusArr   " +Var.user_upgrade_statusArr);
                        Log.i("Main", "user_usernameArr   " +Var.user_usernameArr);
                        Log.i("Main", "user_userpic_urlArr   " +Var.user_userpic_urlArr);*/
        } else {
            returnStr = "not response";
            return returnStr;
        }
    } catch (Exception e) {
        e.printStackTrace();
        returnStr = "not response";
        return returnStr;
    }
    return returnStr;
}

From source file:it.intecs.pisa.toolbox.util.URLReader.java

public static Object getFullURLContent(String urlString) throws Exception {

    String returnString = "";

    URL url = null;/*from  ww  w. j  av a  2 s.  co m*/
    URLConnection connection = null;

    // Open Connection
    try {
        url = new URL(urlString);
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    }

    try {
        connection = url.openConnection();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    HttpURLConnection httpConn = (HttpURLConnection) connection;
    try {

        StreamSource source = new StreamSource(httpConn.getInputStream());

        TransformerFactory fac = TransformerFactory.newInstance();
        Transformer trans = null;
        StreamResult res = new StreamResult(new StringWriter());
        try {
            trans = fac.newTransformer();
        } catch (TransformerConfigurationException ex) {
            ex.printStackTrace();
        }
        try {

            trans.transform(source, res);
        } catch (TransformerException ex) {
            ex.printStackTrace();
        }
        StringWriter w = (StringWriter) res.getWriter();

        returnString = w.toString();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return returnString;
}

From source file:com.magnet.plugin.helpers.URLHelper.java

public static InputStream loadUrl(final String url) throws Exception {
    final InputStream[] inputStreams = new InputStream[] { null };
    final Exception[] exception = new Exception[] { null };
    Future<?> downloadThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
        public void run() {
            try {
                HttpURLConnection connection;
                if (ApplicationManager.getApplication() != null) {
                    connection = HttpConfigurable.getInstance().openHttpConnection(url);
                } else {
                    connection = (HttpURLConnection) new URL(url).openConnection();
                    connection.setReadTimeout(Rest2MobileConstants.CONNECTION_TIMEOUT);
                    connection.setConnectTimeout(Rest2MobileConstants.CONNECTION_TIMEOUT);
                }/*  www .j  av a 2 s. com*/
                connection.connect();

                inputStreams[0] = connection.getInputStream();
            } catch (IOException e) {
                exception[0] = e;
            }
        }
    });

    try {
        downloadThreadFuture.get(5, TimeUnit.SECONDS);
    } catch (TimeoutException ignored) {
    }

    if (!downloadThreadFuture.isDone()) {
        downloadThreadFuture.cancel(true);
        throw new ConnectionException(IdeBundle.message("updates.timeout.error"));
    }

    if (exception[0] != null)
        throw exception[0];
    return inputStreams[0];
}

From source file:Main.java

public static String simplePost(String url, Bundle params, String method)
        throws MalformedURLException, IOException {
    OutputStream os;// ww  w .j  a  va 2s.c  om

    System.setProperty("http.keepAlive", "false");
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " agent");

    conn.setRequestMethod(method);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    //conn.setRequestProperty("Connection", "Keep-Alive");

    conn.connect();

    os = new BufferedOutputStream(conn.getOutputStream());
    os.write(encodePostParams(params).getBytes());
    os.flush();

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:connector.ISConnector.java

public static JSONObject processRequest(String servlet, byte[] query) {
    JSONObject response = null;//from   w w  w.j  a v a  2  s  .  c om
    if (servlet != null && !servlet.startsWith("/"))
        servlet = "/" + servlet;
    try {
        // Establish HTTP connection with Identity Service
        URL url = new URL(CONTEXT_PATH + servlet);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        //Create the form content
        try (OutputStream out = conn.getOutputStream()) {
            out.write(query);
            out.close();
        }

        // Buffer the result into a string
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }

        rd.close();
        conn.disconnect();
        response = (JSONObject) new JSONParser().parse(sb.toString());

    } catch (Exception e) {
        e.printStackTrace();
    }

    return response;
}

From source file:controllers.base.Application.java

public static Result login(String redirectTo, boolean isGuest) {
    if (isGuest) {
        createWebSession();/*from  w ww.ja v a2s  . c o  m*/
    } else {
        String token = request().body().asFormUrlEncoded().get("token")[0];
        String apiKey = Play.application().configuration().getString("rpx.apiKey");
        String data;
        String response = null;
        try {
            data = String.format("token=%s&apiKey=%s&format=json", URLEncoder.encode(token, "UTF-8"),
                    URLEncoder.encode(apiKey, "UTF-8"));
            URL url = new URL("https://rpxnow.com/api/v2/auth_info");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.connect();
            OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            osw.write(data);
            osw.close();
            response = IOUtils.toString(conn.getInputStream());
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }

        JsonNode profile = Json.parse(response).path("profile");
        String identifier = profile.path("identifier").asText();

        WebUser user = WebUser.find.where().like("providerId", identifier).findUnique();

        if (user == null) {
            user = new WebUser().setProviderId(identifier).setProfile(Json.stringify(profile));
            user.save();
        }

        createWebSession(user);
    }

    return postLoginRedirect(redirectTo);
}