Java obtains the website HTML source code through URL

Source: Internet
Author: User
Package COM. WSW. j2se. URL; import Java. io. bytearrayoutputstream; import Java. io. inputstream; import java.net. httpurlconnection; import java.net. URL; /*** obtain the source code of the website through the website domain name URL * @ author administrator **/public class htmlrequest {/*** // *** @ Param ARGs * @ throws malformedurlexception */public static void main (string [] ARGs) throws exception {URL url = new URL ("http://www.ifeng.com"); string urlsource = Geturlsource (URL); system. out. println (urlsource );} /*** // *** obtain the source code of the website through the website domain name URL * @ Param URL * @ return string * @ throws exception */public static string geturlsource (URL) throws exception {httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setrequestmethod ("get"); Conn. setconnecttimeout (5*1000); inputstream instream = Conn. getinputstream (); // get the HTML binary data byte [] D through the input stream ATA = readinputstream (instream); // converts binary data to byte bytes. String htmlsource = new string (data); Return htmlsource ;} /*** // *** convert binary data to byte array * @ Param instream * @ return byte [] * @ throws exception */public static byte [] readinputstream (inputstream instream) throws exception {bytearrayoutputstream outstream = new bytearrayoutputstream (); byte [] buffer = new byte [1204]; int Len = 0; while (LEN = I Nstream. Read (buffer ))! =-1) {outstream. Write (buffer, 0, Len) ;}instream. Close (); Return outstream. tobytearray ();}}

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.