Package zhucepeiyu15;
Import Java.io.BufferedReader;
Import Java.io.ByteArrayOutputStream;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import java.io.UnsupportedEncodingException;
Import java.net.HttpURLConnection;
Import Java.net.URL;
public class Urlresource {
public static void Main (string[] args) {
try {
System.out.println (Urlresource.geturldetail ("http://www.baidu.com", true));
Saveurlfile ("Http://www.baidu.com/img/baidu_jgylogo3.gif", "d:\\1.gif");
System.out.println (Base64.encode (Geturlfiledata ("http://wx.qlogo.cn/mmhead/ver_1/ Kc3aqcrfiadw43znrzignmq76pibzvdxuiaspibe8kwtl3dnf2c6ukoztdsof7ibfmwbfhjic9czjf2a7via5k1uyfgzr8yt6rqu8kxbk15zq9wcte /0 ")));
} catch (Exception e) {
E.printstacktrace ();
}
}
Get network file, dump into filedes, filedes need file suffix name
public static void Saveurlfile (String fileurl,string filedes) throws Exception
{
File ToFile = new file (filedes);
if (Tofile.exists ())
{
throw new Exception ("file exist");
Return
}
Tofile.createnewfile ();
FileOutputStream Outimgstream = new FileOutputStream (tofile);
System.out.println (Geturlfiledata (FILEURL));
Outimgstream.write (Geturlfiledata (FILEURL));
Outimgstream.close ();
}
public static string Getbase64urlfiledata (String fileUrl)
{
try {
Return Base64.encode (Geturlfiledata (New String (Base64.decode (FILEURL)));
} catch (Exception e) {
E.printstacktrace ();
}
return null;
}
Get the byte data for a linked address file
public static byte[] Geturlfiledata (String fileUrl) throws Exception
{
URL url = new URL (fileUrl);
HttpURLConnection httpconn = (httpurlconnection) url.openconnection ();
Httpconn.connect ();
InputStream cin = Httpconn.getinputstream ();
Bytearrayoutputstream OutStream = new Bytearrayoutputstream ();
byte[] buffer = new byte[1024];
int len = 0;
while (len = cin.read (buffer))! =-1) {
Outstream.write (buffer, 0, Len);
}
Cin.close ();
byte[] FileData = Outstream.tobytearray ();
Outstream.close ();
return fileData;
}
Gets the character data for the link address, wichsep whether the newline tag
public static string Geturldetail (String Urlstr,boolean withsep) throws Exception
{
URL url = new URL (urlstr);
HttpURLConnection httpconn = (httpurlconnection) url.openconnection ();
Httpconn.connect ();
InputStream cin = Httpconn.getinputstream ();
BufferedReader reader = new BufferedReader (New InputStreamReader (CIN, "UTF-8"));
StringBuffer sb = new StringBuffer ();
String RL = NULL;
while (RL = Reader.readline ()) = null)
{
if (WITHSEP)
{
Sb.append (RL). Append (System.getproperty ("Line.separator"));
}
Else
{
Sb.append (RL);
}
}
return sb.tostring ();
}
}
Java gets binary data from URL