導航:首頁 > 編程語言 > 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下載相關的資料

熱點內容
win7如何修改用戶密碼 瀏覽:169
逆戰輔助銷售網站源碼 瀏覽:100
陝西回收貼片機如何編程 瀏覽:948
以前鮑魚網站里的小說怎麼沒了 瀏覽:267
matlab程序如何調試 瀏覽:915
ps工程文件怎麼發 瀏覽:95
word文件如何批量插入蓋章 瀏覽:548
jscheckbox 瀏覽:338
pics規則文件 瀏覽:644
如何從數據中找出問題和機會 瀏覽:668
寫作投稿在哪個網站好 瀏覽:895
絕代雙驕版本 瀏覽:380
手機app在哪裡找的對象靠譜嗎 瀏覽:919
win10文件默認顯示ck方式 瀏覽:829
如何更改桌面文件圖標 瀏覽:418
word2010如何去掉背景 瀏覽:632
adp文件如何打開 瀏覽:531
ug編程怎麼導出零件 瀏覽:586
asp在線文件管理系統 瀏覽:468
tks文件如何分解 瀏覽:132

友情鏈接