日期:2014-05-20  浏览次数:20752 次

关于获取网页源代码的问题!!
public void getHtmlFromURL2(String str) {

try {

URL url = new URL(str);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setDoInput(true);

conn.connect();

InputStream is = conn.getInputStream();

BufferedInputStream bis = new BufferedInputStream(is);

ByteArrayBuffer baf = new ByteArrayBuffer(100);

int current = 0;

while ((current = bis.read()) != -1) {

baf.append((byte) current);

}

is.close();

conn.disconnect();

URL_DATA = newString(baf.toByteArray(), "utf-8");

} catch (Exception e) {

URL_DATA = e.getMessage();

}

}
上面是源代码,当我第一次调用可以传入网纸是http://musicapi.sinaapp.com/s.php?q=练习 刘德华&callback=? 
是可以返回正确的Json数据,

[{"url":"http://zhangmenshiting.baidu.com/data2/music/5403280/5403280.mp3?xcode=1c24a1233425ad0b586066d0145f7207&mid=0.81987216767637"},{"url":"http://zhangmenshiting2.baidu.com/data2/music/1441450/1441450.mp3?xcode=1c24a1233425ad0b586066d0145f7207&mid=0.81987216767637"}]%

但我点击第二首歌比如是 http://musicapi.sinaapp.com/s.php?q=暗里首迷 刘德华&callback=? 
返回的数据还是原来的“练习”的下载地址

[{"url":"http://zhangmenshiting.baidu.com/data2/music/5403280/5403280.mp3?xcode=1c24a1233425ad0b586066d0145f7207&mid=0.81987216767637"},{"url":"http://zhangmenshiting2.baidu.com/data2/music/1441450/1441450.mp3?xcode=1c24a1233425ad0b586066d0145f7207&mid=0.81987216767637"}]%E9%97%AE+%E6%A2%81%E9%9D%99%E8%8C%B9&callback

而且在后面加了%E9%97%AE+%E6%A2%81%E9%9D%99%E8%8C%B9&callback
导致下面的解析出错。请问一下是什么原因呢?


------解决方案--------------------
Java code

public void getHtmlFromURL2(String str) {
        String URL_DATA=null;
        try {

        URL url = new URL(str);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setDoInput(true);

        conn.connect();

        InputStream is = conn.getInputStream();

        BufferedInputStream bis = new BufferedInputStream(is);

        ByteArrayBuffer baf = new ByteArrayBuffer(100);

        int current = 0;

        while ((current = bis.read()) != -1) {

        baf.write((byte) current);
        
        }

        is.close();

        conn.disconnect();

        URL_DATA = new String(baf.toByteArray(), "utf-8");
        System.out .print(URL_DATA);

        } catch (Exception e) {

        URL_DATA = e.getMessage();

        }
        
        }