首页 > 代码库 > java从url里获取二进制数据

java从url里获取二进制数据

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();
}
}

//获取网络文件,转存到fileDes中,fileDes需要带文件后缀名
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;
}
//获取链接地址文件的byte数据
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 = http://www.mamicode.com/outStream.toByteArray();
outStream.close();
return fileData;
}

//获取链接地址的字符数据,wichSep是否换行标记
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从url里获取二进制数据