Using the httpurlconnection object, we can obtain webpage data from the network.
URL url = new URL ("http://www.sohu.com ");
Httpurlconnection conn = (httpurlconnection) URL. openconnection ();
Conn. setconnecttimeout (5*1000); // sets the connection timeout.
Conn. setrequestmethod ("get"); // initiate a request in get Mode
If (conn. getresponsecode ()! = 200) throw new runtimeexception ("request URL failed ");
Inputstream is = conn. getinputstream (); // gets the input stream returned by the network.
String result = readdata (is, "GBK ");
Conn. Disconnect ();
// The first parameter is the input stream, and the second parameter is character set encoding.
Public static string readdata (inputstream insream, string charsetname) throws exception {
Bytearrayoutputstream outstream = new bytearrayoutputstream ();
Byte [] buffer = new byte [1024];
Int Len =-1;
While (LEN = insream. Read (buffer ))! =-1 ){
Outstream. Write (buffer, 0, Len );
}
Byte [] DATA = outstream. tobytearray ();
Outstream. Close ();
Insream. Close ();
Return new string (data, charsetname );
}
Using the httpurlconnection object, we can obtain file data from the network.
URL url = new URL ("http://photocdn.sohu.com/20100125/Img269812337.jpg ");
Httpurlconnection conn = (httpurlconnection) URL. openconnection ();
Conn. setconnecttimeout (5*1000 );
Conn. setrequestmethod ("get ");
If (conn. getresponsecode ()! = 200) throw new runtimeexception ("request URL failed ");
Inputstream is = conn. getinputstream ();
Readasfile (is, "img269812337.jpg ");
Public static void readasfile (inputstream insream, file) throws exception {
Fileoutputstream outstream = new fileoutputstream (File );
Byte [] buffer = new byte [1024];
Int Len =-1;
While (LEN = insream. Read (buffer ))! =-1 ){
Outstream. Write (buffer, 0, Len );
}
Outstream. Close ();
Insream. Close ();
}