Add the network access permission to the configuration file
<! -- Access internet permissions -->
<Uses-permissionandroid: name = "android. permission. INTERNET"/>
Using the HttpURLConnection object, we can obtain webpage data from the network.
URL url = newURL ("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.
Stringresult = readData (is, "GBK ");
Conn. disconnect ();
// The first parameter is the input stream, and the second parameter is character set encoding.
Public static StringreadData (InputStream inSream, String charsetName) throws Exception {
ByteArrayOutputStreamoutStream = new ByteArrayOutputStream ();
Byte [] buffer = new byte [1024];
Intlen =-1;
While (len = inSream. read (buffer ))! =-1 ){
OutStream. write (buffer, 0, len );
}
Byte [] data = outStream. toByteArray ();
OutStream. close ();
InSream. close ();
Returnnew String (data, charsetName );
}
Using the HttpURLConnection object, we can obtain file data from the network.
URL url = newURL ("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 voidreadAsFile (InputStream inSream, File file) throws Exception {
FileOutputStreamoutStream = new FileOutputStream (file );
Byte [] buffer = new byte [1024];
Intlen =-1; www.2cto.com
While (len = inSream. read (buffer ))! =-1 ){
OutStream. write (buffer, 0, len );
}
OutStream. close ();
InSream. close ();
}
From: com360 blog