我的要求是做 Web 应用程序以获取目标内容,并且必须使用 HttpURLConnection 添加请求标头。
我使用此代码
try{
String urlStr = "http://test/STAM/Login";
url = new URL(urlStr);
urlconn = (HttpURLConnection)url.openConnection();
urlconn.setRequestProperty("Accept-Language","en-us,en;q=0.5");
urlconn.setRequestProperty("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
urlconn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16");
urlconn.connect();
//read the result from the server
rd = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null)
{
sb.append(line + '\n');
}
out.println(sb.toString());
} catch(Exception e) {
e.printStackTrace();
} finally {
//close the connection, set all objects to null
urlconn.disconnect();
rd = null;
sb = null;
wr = null;
urlconn = null;
}
结果是:我的代码将只获取源内容,但无法获取 css、图像文件、javascript 等,因为它将从本地主机加载,例如“http://localhost:8080/test/img/test.gif”而不是“http://test/STAM/img/test.gif”。如果我错了或者你有什么办法可以解决这个问题,请告诉我。
非常感谢。