import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
public class Test
{
private static String songName = "北京北京";
public static void main(String args[])
{
Test getLrc = new Test();
String lrcUrl = getLrc.getLrcUrl(songName);
System.out.println(lrcUrl);
String lrcTxt = getLrc.getLrcText(lrcUrl);
System.out.println(lrcTxt);
}
public String getLrcUrl(String song)
{
String lrcUrl = null;
try
{
String songEnc = toBrowserCode(song, "UTF-8");
System.out.println(songEnc);
Document doc = Jsoup.connect(
"http://www.9ilrc.com/search.php?keyword=" + songEnc
+ "&radio=song").get();
Elements links = doc.select("a[href]");
for (Element link : links)
{
if (toBrowserCode(trim(link.text(), 15), "UTF-8").equals(
songEnc))
{
lrcUrl = link.attr("abs:href");
break;
}
}
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return lrcUrl;
}
public String getLrcText(String url)
{
String lrcTxt = null;
try
{
Document doc = Jsoup.connect(url).get();
Elements links = doc.select("[id]");
for (Element ele : links)
{
if (ele.attr("id").equals("txt"))
{
lrcTxt = ele.text().replace(" ", "\n");
break;
}
}
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return lrcTxt;
}
private static String trim(String s, int width)
{
if (s.length() > width)
return s.substring(0, width - 1) + ".";
else
return s;
}
public String toBrowserCode(String word, String encoding)
throws UnsupportedEncodingException
{
byte[] textByte = word.getBytes(encoding);
StringBuilder strBuilder = new StringBuilder();
for (int j = 0; j < textByte.length; j++)
{
String hexStr = Integer.toHexString(textByte[j] & 0xff);
strBuilder.append("%" + hexStr.toUpperCase());
}
return strBuilder.toString();
}
}