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:Main.java

public static String getHTML(String urlToRead) {
    URL url; // The URL to read
    HttpURLConnection conn; // The actual connection to the web page
    BufferedReader rd; // Used to read results from the web page
    String line; // An individual line of the web page HTML
    String result = ""; // A long string containing all the HTML
    try {/*from  ww  w . j  a  v  a  2  s.co  m*/
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = rd.readLine()) != null) {
            result += line;
        }
        rd.close();
    } catch (Exception e) {
        // e.printStackTrace();
    }
    return result;
}

From source file:com.intuit.tank.harness.AmazonUtil.java

/**
 * @param string/*from w  w  w  . j  a v  a  2s .  c  o m*/
 * @return
 * @throws IOException
 */
private static InputStream getInputStream(String url) throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
    con.setRequestMethod("GET");
    con.setConnectTimeout(3000);
    return con.getInputStream();
}

From source file:com.jts.rest.profileservice.utils.RestServiceHelper.java

/**
 * Makes a get request to the given url and returns the json object
 * @param sessionId/* w  w  w.j  a  v  a  2  s .  com*/
 * @param url
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
public static JSONArray makeGetRequest(String sessionId, String url) throws MalformedURLException, IOException {
    URL endpoint = new URL(url);
    HttpURLConnection urlc = (HttpURLConnection) endpoint.openConnection();
    urlc.setRequestProperty("Authorization", "OAuth " + sessionId);
    urlc.setRequestMethod("GET");
    urlc.setDoOutput(true);
    String output = OauthHelperUtils.readInputStream(urlc.getInputStream());
    urlc.disconnect();
    Object json = JSONValue.parse(output);
    JSONArray jsonArr = (JSONArray) json;
    return jsonArr;
}

From source file:com.francelabs.datafari.utils.SendHttpRequest.java

public static void sendGET(String url, String userAgent) throws IOException {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", userAgent);
    int responseCode = con.getResponseCode();
    logger.debug("GET Response Code :: " + responseCode);
    if (responseCode == HttpURLConnection.HTTP_OK) { // success
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;/*from w w w .  j  av  a2  s. c o m*/
        StringBuffer response = new StringBuffer();

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

        // print result
        logger.debug(response.toString());
    } else {
        logger.debug("GET request not worked");
    }
}

From source file:jmc.util.UtlFbComents.java

public static void getURLComentarios(String url, Long numComents) throws JMCException {

    File f = null;/*from  w  ww .ja va 2s. c o  m*/

    try {
        Properties props = ConfigPropiedades.getProperties("props_config.properties");
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        URL ur = new URL(
                "http://graph.facebook.com/comments?id=" + url + "&limit=" + numComents + "&filter=stream");
        HttpURLConnection cn = (HttpURLConnection) ur.openConnection();

        cn.setRequestProperty("user-agent", props.getProperty("navegador"));
        cn.setInstanceFollowRedirects(false);
        cn.setUseCaches(false);
        cn.connect();

        BufferedReader br = new BufferedReader(new InputStreamReader(cn.getInputStream()));
        String dirTempHtml = props.getProperty("archive_json") + "/";
        File fld = new File(dirTempHtml);

        boolean creado = fld.exists() ? true : fld.mkdir();

        if (creado) {
            String archFile = "archivo.json";
            String archivo = dirTempHtml + archFile;
            String linea = null;

            f = new File(archivo);
            BufferedWriter bw = new BufferedWriter(new FileWriter(f));
            while ((linea = br.readLine()) != null) {
                bw.append(linea);
            }
            bw.close();

            cn.disconnect();

            List<Fbcoment> lfb = Convertidor.getFbcomentObjects(1l, archivo);
            // Fbcoment.actComents(idContenido, lfb);

        } else {
            cn.disconnect();
        }

    } catch (IOException e) {
        throw new JMCException(e);
    }
}

From source file:jmc.util.UtlFbComents.java

public static void getComentarios(Long idContenido, Long numComents) throws JMCException {

    File f = null;//from  w  w  w. java  2 s.  co m

    try {
        Properties props = ConfigPropiedades.getProperties("props_config.properties");
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        URL ur = new URL("http://graph.facebook.com/comments?id="
                + Contenido.getContenido("Where cont_id = '" + idContenido + "'").get(0).getEnlaceURL()
                + "&limit=" + numComents + "&filter=stream");
        HttpURLConnection cn = (HttpURLConnection) ur.openConnection();

        cn.setRequestProperty("user-agent", props.getProperty("navegador"));
        cn.setInstanceFollowRedirects(false);
        cn.setUseCaches(false);
        cn.connect();

        BufferedReader br = new BufferedReader(new InputStreamReader(cn.getInputStream()));
        String dirTempHtml = props.getProperty("archive_json") + "/";
        File fld = new File(dirTempHtml);

        boolean creado = fld.exists() ? true : fld.mkdir();

        if (creado) {
            String archFile = idContenido + ".json";
            String archivo = dirTempHtml + archFile;
            String linea = null;

            f = new File(archivo);
            BufferedWriter bw = new BufferedWriter(new FileWriter(f));
            while ((linea = br.readLine()) != null) {
                bw.append(linea);
            }
            bw.close();

            cn.disconnect();

            List<Fbcoment> lfb = Convertidor.getFbcomentObjects(idContenido, archivo);
            Fbcoment.actComents(idContenido, lfb);

        } else {
            cn.disconnect();
        }

    } catch (IOException e) {
        throw new JMCException(e);
    }
}

From source file:com.android.idearse.Result.java

public static Bitmap getBitmapFromURL(String src) {
    try {/*from   w  w w  . j  a  v  a2  s  .c  om*/
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.linkedin.pinot.controller.helix.ControllerTest.java

public static String sendDeleteRequest(String urlString) throws IOException {
    final long start = System.currentTimeMillis();

    final URL url = new URL(urlString);
    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);/* ww  w  .  j  a va 2s.  c  o  m*/
    conn.setRequestMethod("DELETE");
    conn.connect();

    final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    final long stop = System.currentTimeMillis();

    LOGGER.info(" Time take for Request : " + urlString + " in ms:" + (stop - start));

    return sb.toString();
}

From source file:brainleg.app.util.AppWeb.java

public static String post(String url, NameValuePair[] postParameters)
        throws RequestRejectedException, IOException {
    HttpConfigurable.getInstance().prepareURL(getUrl("api/proxyTest"));

    HttpURLConnection connection = doPost(url, join(Arrays.asList(postParameters)));
    int responseCode = connection.getResponseCode();

    String responseText;// w  w w.j a va  2  s.c  om

    InputStream is = new BufferedInputStream(connection.getInputStream());
    try {
        responseText = readFrom(is);
    } finally {
        is.close();
    }

    if (responseCode != HttpURLConnection.HTTP_OK) {
        // if this is 400 this is an application error (something is rejected by the app)
        if (responseCode == 400 && responseText != null) {
            //normally we return error messages like this: REQUIRED_PARAM_MISSING:Required parameters missing
            List<String> tokens = Lists
                    .newArrayList(Splitter.on(":").omitEmptyStrings().trimResults().split(responseText));
            if (tokens.isEmpty()) {
                throw new RequestRejectedException();
            } else if (tokens.size() == 1) {
                throw new RequestRejectedException(tokens.get(0), null);
            } else {
                throw new RequestRejectedException(tokens.get(0), tokens.get(1));
            }
        } else {
            throw new IOException("response code from server: " + responseCode);
        }
    } else {
        return responseText;
    }
}

From source file:editor.util.URLUtil.java

public static String sendPost(String url, String data) throws Exception {

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");

    // Send post request
    con.setDoOutput(true);/*ww w .  ja v  a 2  s  .c  om*/
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(data);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    return response.toString();
}