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:core.Utility.java

private static ArrayList<String> getSynonymsWiktionary(String _word) throws MalformedURLException, IOException {
    ArrayList<String> _list = new ArrayList();
    try {/*  w  w  w.  j ava 2 s  . co  m*/

        URL url = new URL("http://www.igrec.ca/project-files/wikparser/wikparser.php?word=" + _word
                + "&query=syn&lang=en");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

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

        String output;
        while ((output = br.readLine()) != null) {
            boolean isEmpty = output.contains("No listed synonyms.")
                    || output.contains("ERROR: The Wiktionary API did not return a page for that word.");

            if (isEmpty) {
                conn.disconnect();
                return _list;
            } else {
                String[] arr = output.trim().split(" ");
                for (String s : arr) {
                    if (s.length() > 2) {
                        _list.add(s);
                    }
                }
            }
        }

        conn.disconnect();

    } catch (MalformedURLException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    }
    return _list;
}

From source file:org.pixmob.fm2.util.HttpUtils.java

/**
 * Open the {@link InputStream} of an Http response. This method supports
 * GZIP responses.//ww w.ja va2s . com
 */
public static InputStream getInputStream(HttpURLConnection conn) throws IOException {
    final List<String> contentEncodingValues = conn.getHeaderFields().get("Content-Encoding");
    if (contentEncodingValues != null) {
        for (final String contentEncoding : contentEncodingValues) {
            if (contentEncoding != null && contentEncoding.contains("gzip")) {
                return new GZIPInputStream(conn.getInputStream());
            }
        }
    }
    return conn.getInputStream();
}

From source file:io.fares.junit.soapui.outside.test.SoapUIMockRunnerTest.java

public static String testMockService(String endpoint) throws MalformedURLException, IOException {

    HttpURLConnection con = (HttpURLConnection) new URL(endpoint).openConnection();
    con.setRequestMethod("POST");
    con.addRequestProperty("Accept", "application/soap+xml");
    con.addRequestProperty("Content-Type", "application/soap+xml");
    con.setDoOutput(true);//from  ww w. j a  v  a 2  s  .  c  o  m
    con.getOutputStream().write(
            "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\"><soap:Header/><soap:Body><GetWeather xmlns=\"http://www.webserviceX.NET\"><CityName>Brisbane</CityName></GetWeather></soap:Body></soap:Envelope>"
                    .getBytes("UTF-8"));
    InputStream is = con.getInputStream();
    StringWriter writer = new StringWriter();
    IOUtils.copy(is, writer, "UTF-8");
    String rs = writer.toString();
    LOG.fine(rs);
    return rs;

}

From source file:net.kourlas.voipms_sms.Utils.java

/**
 * Retrieves a JSON object from the specified URL.
 * <p/>//from w  ww  .  ja va  2 s. co  m
 * Note that this is a blocking method; it should not be called from the URI thread.
 *
 * @param urlString The URL to retrieve the JSON from.
 * @return The JSON object at the specified URL.
 * @throws IOException   if a connection to the server could not be established.
 * @throws JSONException if the server did not return valid JSON.
 */
public static JSONObject getJson(String urlString) throws IOException, JSONException {
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setReadTimeout(10000);
    connection.setConnectTimeout(15000);
    connection.setRequestMethod("GET");
    connection.setDoInput(true);
    connection.connect();

    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
    StringBuilder data = new StringBuilder();
    String newLine = System.getProperty("line.separator");
    String line;
    while ((line = reader.readLine()) != null) {
        data.append(line);
        data.append(newLine);
    }
    reader.close();

    return new JSONObject(data.toString());
}

From source file:com.thomaskuenneth.openweathermapweather.WeatherUtils.java

public static String getFromServer(String url) throws MalformedURLException, IOException {
    StringBuilder sb = new StringBuilder();
    URL _url = new URL(url);
    HttpURLConnection httpURLConnection = (HttpURLConnection) _url.openConnection();
    String contentType = httpURLConnection.getContentType();
    String charSet = "ISO-8859-1";
    if (contentType != null) {
        Matcher m = PATTERN_CHARSET.matcher(contentType);
        if (m.matches()) {
            charSet = m.group(1);/*w w  w  . j  a  v a  2  s. c  o m*/
        }
    }
    final int responseCode = httpURLConnection.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream(),
                charSet);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        try {
            bufferedReader.close();
        } catch (IOException ex) {
            LOGGER.log(Level.SEVERE, "getFromServer()", ex);
        }
    }
    httpURLConnection.disconnect();
    return sb.toString();
}

From source file:com.cyphermessenger.client.SyncRequest.java

private static CypherContact manageContact(CypherSession session, String contactName, boolean add)
        throws IOException, APIErrorException {
    String action = "block";
    if (add) {//from   w  ww.j  a  va2 s  .  c o  m
        action = "add";
    }
    String[] keys = new String[] { "action", "contactName" };
    String[] vals = new String[] { action, contactName };

    HttpURLConnection conn = doRequest("contact", session, keys, vals);
    if (conn.getResponseCode() != 200) {
        throw new IOException("Server error");
    }

    InputStream in = conn.getInputStream();
    JsonNode node = MAPPER.readTree(in);
    conn.disconnect();
    int statusCode = node.get("status").asInt();
    if (statusCode == StatusCode.OK && add) {
        long userID = node.get("contactID").asLong();
        long keyTimestamp = node.get("keyTimestamp").asLong();
        long contactTimestamp = node.get("contactTimestamp").asLong();
        ECKey key = Utils.decodeKey(node.get("publicKey").asText());
        key.setTime(keyTimestamp);
        boolean isFirst = node.get("isFirst").asBoolean();
        return new CypherContact(contactName, userID, key, keyTimestamp, CypherContact.ACCEPTED,
                contactTimestamp, isFirst);
    } else {
        boolean isFirst = node.get("isFirst").asBoolean();
        String status;
        switch (statusCode) {
        case StatusCode.CONTACT_WAITING:
            status = CypherContact.WAITING;
            break;
        case StatusCode.OK:
        case StatusCode.CONTACT_BLOCKED:
            status = CypherContact.BLOCKED;
            break;
        case StatusCode.CONTACT_DENIED:
            status = CypherContact.DENIED;
            break;
        default:
            throw new APIErrorException(statusCode);
        }
        return new CypherContact(contactName, null, null, null, status, null, isFirst);
    }
}

From source file:ly.stealth.punxsutawney.Marathon.java

private static JSONObject sendRequest(String uri, String method, JSONObject json) throws IOException {
    URL url = new URL(Marathon.url + uri);
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    try {/*from  w w w  . j  a v  a 2  s.c om*/
        c.setRequestMethod(method);

        if (method.equalsIgnoreCase("POST")) {
            byte[] body = json.toString().getBytes("utf-8");
            c.setDoOutput(true);
            c.setRequestProperty("Content-Type", "application/json");
            c.setRequestProperty("Content-Length", "" + body.length);
            c.getOutputStream().write(body);
        }

        return (JSONObject) JSONValue.parse(new InputStreamReader(c.getInputStream(), "utf-8"));
    } catch (IOException e) {
        if (c.getResponseCode() == 404 && method.equals("GET"))
            return null;

        ByteArrayOutputStream response = new ByteArrayOutputStream();
        InputStream err = c.getErrorStream();
        if (err == null)
            throw e;

        Util.copyAndClose(err, response);
        IOException ne = new IOException(e.getMessage() + ": " + response.toString("utf-8"));
        ne.setStackTrace(e.getStackTrace());
        throw ne;
    } finally {
        c.disconnect();
    }
}

From source file:br.eb.ime.pfc.domain.GeoServerCommunication.java

private static void redirectStream(String urlName, HttpServletRequest request, HttpServletResponse response) {
    URL url = null;/* w  w w. j  a v  a  2  s  . c  o m*/
    try {
        url = new URL(urlName);
    } catch (MalformedURLException e) {
        //Internal error, the user will receive no data.
        sendError(HTTP_STATUS.BAD_REQUEST, response);
        return;
    }
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.addRequestProperty("Authorization", "Basic " + BASE64_AUTHORIZATION);
        //conn.setRequestMethod("GET");
        //conn.setDoOutput(true);
        conn.connect();
    } catch (IOException e) {
        sendError(HTTP_STATUS.INTERNAL_ERROR, response);
        return;
    }

    try (InputStream is = conn.getInputStream(); OutputStream os = response.getOutputStream()) {
        response.setContentType(conn.getContentType());
        IOUtils.copy(is, os);
    } catch (IOException e) {
        request.getServletContext().log("IO");
        sendError(HTTP_STATUS.INTERNAL_ERROR, response);
        return;
    } finally { //Close connection to save resources
        conn.disconnect();
    }
}

From source file:Main.java

static public String downloadFile(String downloadUrl, String fileName, String dir) throws IOException {
    URL url = new URL(downloadUrl);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);/*from   www  . j a v  a 2  s  .c  om*/
    urlConnection.connect();
    int code = urlConnection.getResponseCode();
    if (code > 300 || code == -1) {
        throw new IOException("Cannot read url: " + downloadUrl);
    }
    String filePath = prepareFilePath(fileName, dir);
    String tmpFilePath = prepareTmpFilePath(fileName, dir);
    FileOutputStream fileOutput = new FileOutputStream(tmpFilePath);
    BufferedInputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
    byte[] buffer = new byte[1024];
    int bufferLength;
    while ((bufferLength = inputStream.read(buffer)) > 0) {
        fileOutput.write(buffer, 0, bufferLength);
    }
    fileOutput.close();
    // move tmp to destination
    copyFile(new File(tmpFilePath), new File(filePath));
    return filePath;
}

From source file:com.cloudera.hoop.client.fs.HoopFileSystem.java

/**
 * Convenience method that JSON Parses the <code>InputStream</code> of a <code>HttpURLConnection</code>.
 *
 * @param conn the <code>HttpURLConnection</code>.
 * @return the parsed JSON object.//from   w  ww .  j av a  2 s. co  m
 * @throws IOException thrown if the <code>InputStream</code> could not be JSON parsed.
 */
private static Object jsonParse(HttpURLConnection conn) throws IOException {
    try {
        JSONParser parser = new JSONParser();
        return parser.parse(new InputStreamReader(conn.getInputStream()));
    } catch (ParseException ex) {
        throw new IOException("JSON parser error, " + ex.getMessage(), ex);
    }
}