求java获取网页源代码

URLConnectionuc;FileWriterfw;try{URLurl=newURL(str1);uc=url.openConnection();Buffered... URLConnection uc;
FileWriter fw;
try {
URL url = new URL(str1);
uc = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream())); //获取源文件
fw = new FileWriter("document\\scanstyle.txt"); //存入本地文件中
while(true){
String temp = br.readLine();
if(temp == null) break;
fw.write(temp);
}
fw.close();
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
以上是简单的获取网页源代码的JAVA代码,我现在想问的是如果一个网站地址出现HTTP-500错误的时候,如何获得其源代码.
相当于在IE-页面-查看源文件中的信息.(包括服务器给出的出错信息)..
分不够可以加..

正常的我已经会获取了.我上面写的代码就可以.
我现在主要是想获得服务器的出错信息.有办法实现吗?
展开
 我来答
寻找逆流的鱼
2010-05-27 · TA获得超过497个赞
知道小有建树答主
回答量:397
采纳率:0%
帮助的人:255万
展开全部
其实你没理解http协议,你能获取html源码,就表明你http协议是成功的,是状态码是200,500就表示网站内部出错了,你也没办法
给你一段代码,这是我写的,应该可以获取正常的
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class WebClient {
public static String getWebContent(String urlString, final String charset,
int timeout) throws IOException {
if (urlString == null || urlString.length() == 0) {
return null;
}
urlString = (urlString.startsWith("http://") || urlString
.startsWith("https://")) ? urlString : ("http://" + urlString)
.intern();
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn
.setRequestProperty(
"User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
conn.setRequestProperty("Accept", "text/html");
conn.setConnectTimeout(timeout);
try {
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input, charset));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\r\n");
}
if (reader != null) {
reader.close();
}
if (conn != null) {
conn.disconnect();
}
return sb.toString();

}

public static String getWebContent(String urlString) throws IOException {
return getWebContent(urlString, "iso-8859-1", 5000);
}

public static void main(String[] args) throws IOException {
String s = getWebContent("http://www.baidu.com");
s = new String(s.getBytes("iso-8859-1"), "gb2312");
System.out.println(s);
}
}

=====
获取conn.getResponseCode()是500的状态码不就行了吗
扒扒组
2010-05-27 · TA获得超过176个赞
知道答主
回答量:135
采纳率:0%
帮助的人:74.3万
展开全部
源代码你应该获取不到吧。。。你获取的是服务器发过来经过处理过的代码
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式