[英]Java: Download from an URL
有人可以嘗試我的密碼嗎? 幾天前它在工作,現在卻不行。 我沒有進行任何修改,因此我懷疑那邊的網站管理員阻止了我。 有人可以幫我看看嗎? 這是我學校項目的一部分。
public class Cost extends TimerTask{
public void run() {
Calendar rightNow = Calendar.getInstance();
Integer hour = rightNow.get(Calendar.HOUR_OF_DAY);
if (hour==1) {
try {
URL tariff = new URL("http://www.emcsg.com/MarketData/PriceInformation?downloadRealtime=true");
ReadableByteChannel tar = Channels.newChannel(tariff.openStream());
FileOutputStream fos = new FileOutputStream("test.csv");
fos.getChannel().transferFrom(tar, 0, 1<<24);
} catch (IOException ex) {
Logger.getLogger(Cost.class.getName()).log(Level.SEVERE, null, ex);
}
}
else {
}
}
}
首先,清理您的IO異常,因為這可能掩蓋了問題-檢查是否可以寫入D:。
如果由於用戶代理標頭而被站點阻止:
這將顯示您的用戶代理標題: http : //pgl.yoyo.org/http/browser-headers.php 。 然后, 設置Java URLConnection的設置用戶代理的答案將告訴您如何設置標頭。
您要么需要在實例化URL和打開流之間添加一個步驟:
URL tariff = new URL("http://www.emcsg.com/MarketData/PriceInformation?downloadRealtime=true");
java.net.URLConnection c = tariff.openConnection();
c.setRequestProperty("User-Agent", " USER AGENT STRING HERE ");
ReadableByteChannel tar = Channels.newChannel(c.getInputStream());
或者您可以嘗試這樣做:
System.setProperty("http.agent", " USER AGENT STRING HERE ");
在調用openStream()
之前的某個時間。
編輯:這為我工作。 您可以嘗試運行它,讓我們知道輸出嗎?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class TestURL {
public static void main(String[] args) {
try {
URL tariff = new URL("http://www.emcsg.com/MarketData/PriceInformation?downloadRealtime=true");
URLConnection c = tariff.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
System.out.println(br.readLine());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
我檢查了您的代碼並運行它,沒有問題,一切正常。 您在代理后面工作嗎?
在這種情況下,您必須對其進行配置:
System.setProperty("http.proxyHost", "my.proxy.name");
System.setProperty("http.proxyPort", "8080");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.