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:com.pureinfo.srm.outlay.action.SearchCheckCodeAction.java

/**
 * /*from   w w w . j  a  v a  2s  .c o  m*/
 * @param strUrl
 * @param strPostRequest
 * @return
 */
public static String getPageContent(String strUrl, String strPostRequest) {
    //
    StringBuffer buffer = new StringBuffer();
    System.setProperty("sun.net.client.defaultConnectTimeout", "5000");
    System.setProperty("sun.net.client.defaultReadTimeout", "5000");
    try {
        URL newUrl = new URL(strUrl);
        HttpURLConnection hConnect = (HttpURLConnection) newUrl.openConnection();
        //POST
        if (strPostRequest.length() > 0) {
            hConnect.setDoOutput(true);
            OutputStreamWriter out = new OutputStreamWriter(hConnect.getOutputStream());
            out.write(strPostRequest);
            out.flush();
            out.close();
        }
        //
        BufferedReader rd = new BufferedReader(new InputStreamReader(hConnect.getInputStream()));
        int ch;
        for (int length = 0; (ch = rd.read()) > -1; length++)
            buffer.append((char) ch);
        rd.close();
        hConnect.disconnect();
        return buffer.toString().trim();
    } catch (Exception e) {
        // return ":";
        return null;
    } finally {
        buffer.setLength(0);
    }
}

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

private static void forceUpdate() throws IOException, VcdiffDecodeException {
    File backupFile = new File(DATA_DIR, "helios.jar.bak");
    try {/*from  w  w  w. j av a2  s .c  om*/
        Files.copy(IMPL_FILE.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException exception) {
        // We're going to wrap it so end users know what went wrong
        throw new IOException(String.format("Could not back up Helios implementation (%s %s, %s %s)",
                IMPL_FILE.canRead(), IMPL_FILE.canWrite(), backupFile.canRead(), backupFile.canWrite()),
                exception);
    }
    URL latestVersion = new URL("https://ci.samczsun.com/job/Helios/lastStableBuild/buildNumber");
    HttpURLConnection connection = (HttpURLConnection) latestVersion.openConnection();
    if (connection.getResponseCode() == 200) {
        boolean aborted = false;

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        copy(connection.getInputStream(), outputStream);
        String version = new String(outputStream.toByteArray(), "UTF-8");
        System.out.println("Latest version: " + version);
        int intVersion = Integer.parseInt(version);

        loop: while (true) {
            int buildNumber = loadHelios().buildNumber;
            int oldBuildNumber = buildNumber;
            System.out.println("Current Helios version is " + buildNumber);

            if (buildNumber < intVersion) {
                while (buildNumber <= intVersion) {
                    buildNumber++;
                    URL status = new URL("https://ci.samczsun.com/job/Helios/" + buildNumber + "/api/json");
                    HttpURLConnection con = (HttpURLConnection) status.openConnection();
                    if (con.getResponseCode() == 200) {
                        JsonObject object = Json.parse(new InputStreamReader(con.getInputStream())).asObject();
                        if (object.get("result").asString().equals("SUCCESS")) {
                            JsonArray artifacts = object.get("artifacts").asArray();
                            for (JsonValue value : artifacts.values()) {
                                JsonObject artifact = value.asObject();
                                String name = artifact.get("fileName").asString();
                                if (name.contains("helios-") && !name.contains(IMPLEMENTATION_VERSION)) {
                                    JOptionPane.showMessageDialog(null,
                                            "Bootstrapper is out of date. Patching cannot continue");
                                    aborted = true;
                                    break loop;
                                }
                            }
                            URL url = new URL("https://ci.samczsun.com/job/Helios/" + buildNumber
                                    + "/artifact/target/delta.patch");
                            con = (HttpURLConnection) url.openConnection();
                            if (con.getResponseCode() == 200) {
                                File dest = new File(DATA_DIR, "delta.patch");
                                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                                copy(con.getInputStream(), byteArrayOutputStream);
                                FileOutputStream fileOutputStream = new FileOutputStream(dest);
                                fileOutputStream.write(byteArrayOutputStream.toByteArray());
                                fileOutputStream.close();
                                File cur = IMPL_FILE;
                                File old = new File(IMPL_FILE.getAbsolutePath() + "." + oldBuildNumber);
                                if (cur.renameTo(old)) {
                                    VcdiffDecoder.decode(old, dest, cur);
                                    old.delete();
                                    dest.delete();
                                    continue loop;
                                } else {
                                    throw new IllegalArgumentException("Could not rename");
                                }
                            }
                        }
                    } else {
                        JOptionPane.showMessageDialog(null,
                                "Server returned response code " + con.getResponseCode() + " "
                                        + con.getResponseMessage() + "\nAborting patch process",
                                null, JOptionPane.INFORMATION_MESSAGE);
                        aborted = true;
                        break loop;
                    }
                }
            } else {
                break;
            }
        }

        if (!aborted) {
            int buildNumber = loadHelios().buildNumber;
            System.out.println("Running Helios version " + buildNumber);
            JOptionPane.showMessageDialog(null, "Updated Helios to version " + buildNumber + "!");
            Runtime.getRuntime().exec(new String[] { "java", "-jar", BOOTSTRAPPER_FILE.getAbsolutePath() });
        } else {
            try {
                Files.copy(backupFile.toPath(), IMPL_FILE.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException exception) {
                // We're going to wrap it so end users know what went wrong
                throw new IOException("Critical Error! Could not restore Helios implementation to original copy"
                        + "Try relaunching the Bootstrapper. If that doesn't work open a GitHub issue with details",
                        exception);
            }
        }
        System.exit(0);
    } else {
        throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage());
    }
}

From source file:it.feio.android.omninotes.utils.GeocodeHelper.java

public static ArrayList<String> autocomplete(String input) {
    ArrayList<String> resultList = null;

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {//from w w  w. j  av a  2  s  .c  o m
        StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
        sb.append("?key=" + API_KEY);
        sb.append("&input=" + URLEncoder.encode(input, "utf8"));

        URL url = new URL(sb.toString());
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
    } catch (MalformedURLException e) {
        Ln.e(e, "Error processing Places API URL");
        return resultList;
    } catch (IOException e) {
        Ln.e(e, "Error connecting to Places API");
        return resultList;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    try {
        // Create a JSON object hierarchy from the results
        JSONObject jsonObj = new JSONObject(jsonResults.toString());
        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

        // Extract the Place descriptions from the results
        resultList = new ArrayList<String>(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {
            resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
        }
    } catch (JSONException e) {
        Ln.e(LOG_TAG, "Cannot process JSON results", e);
    }

    return resultList;
}

From source file:com.gson.util.HttpKit.java

/**
 * @description /*from ww  w  .j a v a2  s.  c  o  m*/
 * ??: POST 
 * @return       : 
 * @throws IOException 
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws KeyManagementException 
 */
public static String post(String url, String params)
        throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, IOException {
    HttpURLConnection http = null;
    if (isHttps(url)) {
        http = initHttps(url, _POST, null);
    } else {
        http = initHttp(url, _POST, null);
    }
    OutputStream out = http.getOutputStream();
    out.write(params.getBytes(DEFAULT_CHARSET));
    out.flush();
    out.close();

    InputStream in = http.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    StringBuffer bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null) {
        bufferRes.append(valueString);
    }
    in.close();
    if (http != null) {
        http.disconnect();// 
    }
    return bufferRes.toString();
}

From source file:Main.java

/**
 * Make an HTTP request to the given URL and return a String as the response.
 *//*from w  w w .  j  a v  a  2  s . com*/
private static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    // If the URL is null, then return early.
    if (url == null) {
        return jsonResponse;
    }

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        /*
        If the request was successful (response code 200),
        then read the input stream and parse the response.
         */
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            //handle exception
        }
    } catch (IOException e) {
        //handle exception
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return jsonResponse;
}

From source file:org.immopoly.android.helper.WebHelper.java

public static JSONObject getHttpsData(URL url, boolean signed, Context context) throws ImmopolyException {
    JSONObject obj = null;/* w  ww  . j a  v  a2  s .co m*/
    if (Settings.isOnline(context)) {
        HttpURLConnection request;
        try {
            request = (HttpURLConnection) url.openConnection();
            request.addRequestProperty("User-Agent",
                    "immopoly android client " + ImmopolyActivity.getStaticVersionInfo());

            if (signed)
                OAuthData.getInstance(context).consumer.sign(request);

            request.setConnectTimeout(SOCKET_TIMEOUT);
            request.connect();

            InputStream in = new BufferedInputStream(request.getInputStream());
            String s = readInputStream(in);
            JSONTokener tokener = new JSONTokener(s);
            return new JSONObject(tokener);
        } catch (JSONException e) {
            throw new ImmopolyException("Kommunikationsproblem (beim lesen der Antwort)", e);
        } catch (MalformedURLException e) {
            throw new ImmopolyException("Kommunikationsproblem (fehlerhafte URL)", e);
        } catch (OAuthMessageSignerException e) {
            throw new ImmopolyException("Kommunikationsproblem (Signierung)", e);
        } catch (OAuthExpectationFailedException e) {
            throw new ImmopolyException("Kommunikationsproblem (Sicherherit)", e);
        } catch (OAuthCommunicationException e) {
            throw new ImmopolyException("Kommunikationsproblem (Sicherherit)", e);
        } catch (IOException e) {
            throw new ImmopolyException("Kommunikationsproblem", e);
        }
    } else
        throw new ImmopolyException("Kommunikationsproblem (Offline)");
}

From source file:com.osbitools.ws.shared.web.BasicWebUtils.java

public static String readGetEx(String url) throws MalformedURLException, IOException {
    String res = "";
    BufferedReader reader = null;

    try {/* w  w w .  ja va  2  s .  co m*/
        HttpURLConnection conn;
        conn = (HttpURLConnection) (new URL(url)).openConnection();

        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String line;

        while ((line = reader.readLine()) != null)
            res += line;

    } finally {
        if (reader != null)
            reader.close();
    }

    return res;
}

From source file:org.apache.brooklyn.util.http.HttpTool.java

/**
 * Closes all streams of the connection, and disconnects it. Ignores all exceptions completely,
 * not even logging them!/*from   w w  w  .j a  v  a2 s  .c  o m*/
 */
public static void closeQuietly(HttpURLConnection connection) {
    try {
        connection.disconnect();
    } catch (Exception e) {
    }
    try {
        connection.getInputStream().close();
    } catch (Exception e) {
    }
    try {
        connection.getOutputStream().close();
    } catch (Exception e) {
    }
    try {
        connection.getErrorStream().close();
    } catch (Exception e) {
    }
}

From source file:com.ibuildapp.romanblack.CataloguePlugin.imageloader.Utils.java

public static String downloadFile(Context context, String url, String md5) {
    final int BYTE_ARRAY_SIZE = 8024;
    final int CONNECTION_TIMEOUT = 30000;
    final int READ_TIMEOUT = 30000;

    try {// w w w .j av a 2 s. c  om
        for (int i = 0; i < 3; i++) {
            URL fileUrl = new URL(URLDecoder.decode(url));
            HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
            connection.setConnectTimeout(CONNECTION_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.connect();

            int status = connection.getResponseCode();

            if (status >= HttpStatus.SC_BAD_REQUEST) {
                connection.disconnect();

                continue;
            }

            BufferedInputStream bufferedInputStream = new BufferedInputStream(connection.getInputStream());
            File file = new File(StaticData.getCachePath(context) + md5);

            if (!file.exists()) {
                new File(StaticData.getCachePath(context)).mkdirs();
                file.createNewFile();
            }

            FileOutputStream fileOutputStream = new FileOutputStream(file, false);
            int byteCount;
            byte[] buffer = new byte[BYTE_ARRAY_SIZE];

            while ((byteCount = bufferedInputStream.read(buffer, 0, BYTE_ARRAY_SIZE)) != -1)
                fileOutputStream.write(buffer, 0, byteCount);

            bufferedInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();

            return file.getAbsolutePath();
        }
    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }

    return null;
}

From source file:software.uncharted.util.HTTPUtil.java

public static String post(String urlToRead, String postData) {
    URL url;//  w ww .j  a v  a  2 s  . com
    HttpURLConnection conn;
    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/json");

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        wr.close();

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[16384];
        InputStream is = conn.getInputStream();
        while ((nRead = is.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        buffer.flush();
        return buffer.toString();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Failed to read URL: " + urlToRead + " <" + e.getMessage() + ">");
    }
    return null;
}