我一直在编写一些Java代码,其中将字符串转换为URL,然后用于下载并输出相应的URL。不幸的是,当我运行这个程序的时候,它就挂掉了。有人有暗示吗?
注意:我使用了导入java.io.*和导入java.net.*
public static boolean htmlOutput(String testURL) throws Exception {
URL myPage2 = new URL(testURL); //converting String to URL
System.out.println(myPage2);
BufferedReader webInput2 = new BufferedReader(
new InputStreamReader(myPage2.openStream()));
String individualLine=null;
String completeInput=null;
while ((individualLine = webInput2.readLine()) != null) {
//System.out.println(inputLine);
System.out.println(individualLine);
completeInput=completeInput+individualLine;
}//end while
webInput2.close();
return true;
}//end htmlOutput()发布于 2013-08-16 15:09:03
虽然这个答案对行动有所帮助,但这是错误的。HttpURLConnection ,所以这不可能是OP的问题。一旦OP移除接受的标记,我就会删除它。]
我的猜测是,您没有在响应流中获得任何信息,因为您试图连接的页面会向您发送重定向响应(即302)。
尝试通过读取响应代码来验证这一点,并在响应头上进行迭代。应该有一个名为Location的头,需要遵循一个新的url。
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int code = connection.getResponseCode();
Map<String, List<String>> map = conn.getHeaderFields();
// iterate over the map and find new url 如果您在让上面的代码片段工作有困难,请看一看工作实例
您可以帮自己一个忙,并使用第三方http客户端(如Apache Http客户端 )来处理重定向,否则您应该手动进行重定向。
https://stackoverflow.com/questions/18275602
复制相似问题