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