Java gets text content from a URL

Source: Internet
Author: User

Original Address https://www.cnblogs.com/myadmin/p/7634262.html

public static string Readfilebyurl (String urlstr) {        string res=null;        try {            url url = new URL (urlstr);              HttpURLConnection conn = (httpurlconnection) url.openconnection ();              Set the timeout time to 3 seconds            conn.setconnecttimeout (3*1000);            Prevents the masking program from crawling and returns 403 error            Conn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 5.0; Windows NT; Digext) ");            Get input stream            InputStream InputStream = Conn.getinputstream ();              res = Readinputstream (InputStream);        } catch (Exception e) {            logger.error ("Failed to get textual content via URL address Exception:" + E);        }        return res;    }
/**     * Get string from input stream     * @param inputstream *     @return     * @throws IOException */Public    static string Readinputstream (InputStream inputstream) throws IOException {          byte[] buffer = new byte[1024];          int len = 0;          Bytearrayoutputstream BOS = new Bytearrayoutputstream ();          while (len = inputstream.read (buffer))! =-1) {              bos.write (buffer, 0, Len);          }          Bos.close ();          System.out.println (New String (Bos.tobytearray (), "Utf-8"));        return new String (Bos.tobytearray (), "Utf-8");    }  

Java gets text content from a URL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.