导航:首页 > 编程语言 > javahttpurl下载

javahttpurl下载

发布时间:2024-09-07 07:56:07

java 获得http下载文件的真实名称

importjava.net.*;
importjava.io.*;
publicclassURLConnectionDemo{
publicstaticvoidmain(String[]args)throwsException{
=newURL("http://www.scp.e.cn/pantoschoolzz/BG/Bord/Message/DownloadMessageAttachment.aspx?ID=215");
URLConnectionuc=url.openConnection();
StringfileName=uc.getHeaderField(6);
fileName=URLDecoder.decode(fileName.substring(fileName.indexOf("filename=")+9),"UTF-8");
System.out.println("文件名为:"+fileName);
System.out.println("文件大小:"+(uc.getContentLength()/1024)+"KB");
Stringpath="D:"+File.separator+fileName;
FileOutputStreamos=newFileOutputStream(path);
InputStreamis=uc.getInputStream();
byte[]b=newbyte[1024];
intlen=0;
while((len=is.read(b))!=-1){
os.write(b,0,len);
}
os.close();
is.close();
System.out.println("下载成功,文件保存在:"+path);
}
}

//输出内容:

文件名为:090602、09-10(1)校历.xls

文件大小:42KB

下载成功,文件保存在:D:90602、09-10(1)校历.xls

❷ Java请求一个URL。获取网站返回的数据。通过POST请求

packagewzh.Http;

importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.io.PrintWriter;
importjava.net.URL;
importjava.net.URLConnection;
importjava.util.List;
importjava.util.Map;

publicclassHttpRequest{
/**
*向指定URL发送GET方法的请求
*
*@paramurl
*发送请求的URL
*@paramparam
*请求参数,请求参数应该是name1=value1&name2=value2的形式。
*@returnURL所代表远程资源的响应结果
*/
publicstaticStringsendGet(Stringurl,Stringparam){
Stringresult="";
BufferedReaderin=null;
try{
StringurlNameString=url+"?"+param;
URLrealUrl=newURL(urlNameString);
//打开和URL之间的连接
URLConnectionconnection=realUrl.openConnection();
//设置通用的请求属性
connection.setRequestProperty("accept","*/*");
connection.setRequestProperty("connection","Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1)");
//建立实际的连接
connection.connect();
//获取所有响应头字段
Map<String,List<String>>map=connection.getHeaderFields();
//遍历所有的响应头字段
for(Stringkey:map.keySet()){
System.out.println(key+"--->"+map.get(key));
}
//定义BufferedReader输入流来读取URL的响应
in=newBufferedReader(newInputStreamReader(
connection.getInputStream()));
Stringline;
while((line=in.readLine())!=null){
result+=line;
}
}catch(Exceptione){
System.out.println("发送GET请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输入流
finally{
try{
if(in!=null){
in.close();
}
}catch(Exceptione2){
e2.printStackTrace();
}
}
returnresult;
}

/**
*向指定URL发送POST方法的请求
*
*@paramurl
*发送请求的URL
*@paramparam
*请求参数,请求参数应该是name1=value1&name2=value2的形式。
*@return所代表远程资源的响应结果
*/
publicstaticStringsendPost(Stringurl,Stringparam){
PrintWriterout=null;
BufferedReaderin=null;
Stringresult="";
try{
URLrealUrl=newURL(url);
//打开和URL之间的连接
URLConnectionconn=realUrl.openConnection();
//设置通用的请求属性
conn.setRequestProperty("accept","*/*");
conn.setRequestProperty("connection","Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1)");
//发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
//获取URLConnection对象对应的输出流
out=newPrintWriter(conn.getOutputStream());
//发送请求参数
out.print(param);
//flush输出流的缓冲
out.flush();
//定义BufferedReader输入流来读取URL的响应
in=newBufferedReader(
newInputStreamReader(conn.getInputStream()));
Stringline;
while((line=in.readLine())!=null){
result+=line;
}
}catch(Exceptione){
System.out.println("发送POST请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOExceptionex){
ex.printStackTrace();
}
}
returnresult;
}
}
//函数调用时填入URL和参数(参数非必须)就可以获取返回的数据,发送post请求调用示例
Stringresult=HttpRequest.sendPost("http://api.map..com/telematics/v3/weather?location=%E5%8C%97%E4%BA%AC&output=json&ak=","")

❸ JAVA代码给网站发送HTTP请求时能不能只发送请求而不接受网站返回的数据

你把inputStream给关了行不行

❹ 用java流的方式怎么指定下载到指定目录下

举例代码:

/**
*下载文件。
*@文件的URL
*@paramsavePath保存到的目录
*@paramfileName保存的文件名称
*@paramdescription描述(如:歌曲,专辑封面,歌词等)
*@throwsIOException
*/
publicstaticvoiddownLoad(StringurlStr,StringsavePath,StringfileName,Stringdescription)throwsIOException
{
URLurl=newURL(urlStr);
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(100000);//设置超时间为10秒
conn.setRequestProperty("User-Agent","Mozilla/4.0(compatible;MSIE5.0;WindowsNT;DigExt)");//防止屏蔽程序抓取而返回403错误

FilesaveDir=newFile(savePath);
Filefile=newFile(saveDir+File.separator+fileName);

try(InputStreaminputStream=conn.getInputStream();
FileOutputStreamfos=newFileOutputStream(file))
{
byte[]flowData=readInputStream(inputStream);
fos.write(flowData);
}catch(Exceptione){
MainFrame.logEvent("字节保存时出现意外:"+e.getMessage());
}
MainFrame.logEvent(description+"下载完成:"+url);
}

MainFrame.logEvent()是我自己弄的日志记录而已,可以忽略不看

❺ java程序下载pdf文件

主要是 URL 和 HttpURLConnection 类的运用,看代码:


importjava.io.DataInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.net.HttpURLConnection;
importjava.net.URL;

publicclassHttpDownloader{

_FILE_URL="http://211.103.156.163/u/cms/www/201511/25051940i6ou.pdf";
privatestaticfinalStringLOCAL_FILE_PATH="D:/some.pdf";//改成你保存文件的路径

publicstaticvoidmain(String[]args){
(REMOTE_FILE_URL,LOCAL_FILE_PATH).download();
}

privateStringremoteFileUrl;
privateStringlocalFilePath;

publicHttpDownloader(StringremoteFileUrl,StringlocalFilePath){
this.remoteFileUrl=remoteFileUrl;
this.localFilePath=localFilePath;
}

publicvoiddownload(){
try{
URLurl=newURL(remoteFileUrl);

=(HttpURLConnection)url.openConnection();
httpURLConnection.setConnectTimeout(5*1000);//5000毫秒内没有连接上则放弃连接
httpURLConnection.connect();//连接
System.out.println("连接URL成功~");

intfileLenght=httpURLConnection.getContentLength();
System.out.println("文件大小:"+(fileLenght/1024.0)+"KB");

System.out.println("开始下载...");
try(DataInputStreamdis=newDataInputStream(httpURLConnection.getInputStream());
FileOutputStreamfos=newFileOutputStream(localFilePath)){
byte[]buf=newbyte[10240];//根据实际情况可以增大buf大小
for(intreadSize;(readSize=dis.read(buf))>0;){
fos.write(buf,0,readSize);
}
System.out.println("下载完毕~");
}catch(IOExceptionex){
System.out.println("下载时出错");
}

httpURLConnection.disconnect();
}catch(IOExceptionex){
System.out.println("URL不存在或者连接超时");
}
}
}

❻ java 使用HttpURLConnection请求服务器,如果发送请求时没有问题,但返回结果时网络断了,如何处理

.setConnectTimeout() 指的是与请求网址的服务器建立连接的超时时间。
setReadTimeout() 指的是建立连接后如果指定时间内服务器没有返回数据的后超时。
503是错误码,能返回就说明服务器返回了response。超时指的是你指定的时间没有收到服务器的response。

不管哪种超时都不有状态码返回。因为返回是在response响应中的,而就是在设定的时间内没有收到响应,才会超时。如果出现超时的话会抛出一个异常。你可以catch超时异常,然后根据需要处理就行了。

❼ 如何用java实现登陆网站--不需打开浏览器

public static void loginBai() {
URL url = null;
HttpURLConnection httpurlconnection = null;
try {
url = new URL("http://www..com/");
httpurlconnection = (HttpURLConnection) url.openConnection();
httpurlconnection.setRequestProperty("User-Agent",
"Internet Explorer");
httpurlconnection.setRequestProperty("Host", "www..com");
httpurlconnection.connect();

String cookie0 = httpurlconnection.getHeaderField("Set-Cookie");

System.out.println(cookie0);//打印出cookie
httpurlconnection.disconnect();
// String cookie0 =
// "BAIDUID=:FG=1;BDSTAT=;
// BDUSE=deleted";
url = new URL("http://passport..com/?login");
String strPost = "username=xxxxxx&password=yyyyyyy&mem_pass=on";
httpurlconnection = (HttpURLConnection) url.openConnection();
httpurlconnection.setFollowRedirects(true);
httpurlconnection.setInstanceFollowRedirects(true);
httpurlconnection.setDoOutput(true); // 需要向服务器写数据
httpurlconnection.setDoInput(true); //
httpurlconnection.setUseCaches(false); // 获得服务器最新的信息
httpurlconnection.setAllowUserInteraction(false);
httpurlconnection.setRequestMethod("POST");
httpurlconnection
.addRequestProperty(
"Accept",
"image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-silverlight, */*");
httpurlconnection
.setRequestProperty("Referer",
"http://passport..com/?login&tpl=mn&u=http%3A//www..com/");
httpurlconnection.setRequestProperty("Accept-Language", "zh-cn");
httpurlconnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
httpurlconnection.setRequestProperty("Accept-Encoding",
"gzip, deflate");
httpurlconnection
.setRequestProperty(
"User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Foxy/1; .NET CLR 2.0.50727;MEGAUPLOAD 1.0)");
httpurlconnection.setRequestProperty("Host", "passport..com");
httpurlconnection.setRequestProperty("Content-Length", strPost
.length()
+ "");
httpurlconnection.setRequestProperty("Connection", "Keep-Alive");
httpurlconnection.setRequestProperty("Cache-Control", "no-cache");
httpurlconnection.setRequestProperty("Cookie", cookie0);
httpurlconnection.getOutputStream().write(strPost.getBytes());
httpurlconnection.getOutputStream().flush();
httpurlconnection.getOutputStream().close();
httpurlconnection.connect();
int code = httpurlconnection.getResponseCode();
System.out.println("code " + code);
String cookie1 = httpurlconnection.getHeaderField("Set-Cookie");
System.out.print(cookie0 + "; " + cookie1);
httpurlconnection.disconnect();
url = new URL("http://www..com/");
httpurlconnection = (HttpURLConnection) url.openConnection();
httpurlconnection.setRequestProperty("User-Agent",
"Internet Explorer");
httpurlconnection.setRequestProperty("Host", "www..com");
httpurlconnection.setRequestProperty("Cookie", cookie0 + "; "
+ cookie1);
httpurlconnection.connect();
InputStream urlStream = httpurlconnection.getInputStream();
BufferedInputStream buff = new BufferedInputStream(urlStream);
Reader r = new InputStreamReader(buff, "gbk");
BufferedReader br = new BufferedReader(r);
StringBuffer strHtml = new StringBuffer("");
String strLine = null;
while ((strLine = br.readLine()) != null) {
strHtml.append(strLine + "\r\n");
}
System.out.print(strHtml.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpurlconnection != null)
httpurlconnection.disconnect();
}
}

呵呵,改了下程序中错误的地方。学习了,原来这样也可以。
以前只知道可以这样做,还从来没有花过心思去做过。
阅读了些代码,真是获益匪浅啊。

程序可以运行了,用户名和密码改为你的帐户就可以直接运行了。可以使用,但不能一直使用啊,如果用多了网络给你个验证码,就是神仙也不行了。

阅读全文

与javahttpurl下载相关的资料

热点内容
java编辑word文件 浏览:149
类似scihub的网站有哪些 浏览:398
ios哪里找小众app 浏览:377
毒霸新闻弹窗是哪个文件 浏览:331
雨林木win10 浏览:881
写好的代码怎么编程小程序 浏览:945
改文件属性软件 浏览:917
linux网卡重启新命令 浏览:216
win10升级工具下 浏览:935
电脑qq怎么传文件到手机qq 浏览:417
被360隔离的文件在哪个文件夹 浏览:971
骷髅教程图 浏览:954
ps淘宝女包修图教程 浏览:568
55公里app 浏览:556
欠费多少充多少为啥还用不了数据 浏览:607
苹果7如何使用万能钥匙 浏览:254
微信文件传送电脑 浏览:600
什么app可以解压百度云rar 浏览:627
苹果6sp换壳 浏览:956
海盗船k70rgb灯光配置文件 浏览:336

友情链接