Public Staticstring Readfilebyurl (String urlstr) {string res=NULL; Try{URL URL=NewURL (URLSTR); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); //set the timeout time to 3 secondsConn.setconnecttimeout (3*1000); //prevents the masking program from crawling and returns a 403 errorConn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 5.0; Windows NT; Digext) "); //Get input streamInputStream InputStream =Conn.getinputstream (); Res=Readinputstream (InputStream); } Catch(Exception e) {logger.error ("Failed to get text content from URL address Exception:" +e); } returnRes; }
/*** Get the string from the input stream *@paramInputStream *@return * @throwsIOException*/ Public StaticString Readinputstream (InputStream inputstream)throwsIOException {byte[] buffer =New byte[1024]; intLen = 0; Bytearrayoutputstream Bos=NewBytearrayoutputstream (); while(len = inputstream.read (buffer))! =-1) {bos.write (buffer,0, Len); } bos.close (); System.out.println (NewString (Bos.tobytearray (), "Utf-8")); return NewString (Bos.tobytearray (), "Utf-8"); }
Java gets text content from a URL