Today, I saw a music interface on the Internet. It happened that some music needed copyright to be heard, so I was ready to toss
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONObject;
public class Main
{
public static void main(String[] args)
{
System.out.println("Please enter a song name\\Singer name");
Scanner scan = new Scanner(System.in);
String scanStr = scan.next();
System.out.println("Getting data");
parseHtml(scanStr);
}
private static void parseHtml(String getText)
{
try
{
URL url = new URL("http://luaapp.cn/music.search.json?key=" + getText + "&page=1");
InputStream in = url.openStream();//openStream() method to access the Internet
InputStreamReader isr = new InputStreamReader(in);
BufferedReader bufr = new BufferedReader(isr);//Read source
StringBuilder sb = new StringBuilder();
String str;
while ((str = bufr.readLine()) != null)
{
sb.append(str);// Splicing the source code obtained together
}
String json =sb.toString();
JSONObject jsonObj= new JSONObject(json);//First get a JSONObject
JSONArray jsonArray = jsonObj.optJSONArray("list");//Use optJSONArray("name") to get a collection
for (int index = 0,count = jsonArray == null ?0: jsonArray.length();index < count;index++)//Traversal of all elements in a collection
{
JSONObject jsonObj2 = jsonArray.optJSONObject(index);
if (jsonObj2 == null)
{
continue;
}
String songMessage = jsonObj2.optString("song");
System.out.println(songMessage);
}
bufr.close();
isr.close();
in.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
In the above example, first create the object url, open the input stream through the url.openStream() method to obtain the InputStreamReader object, then create the BufferedReader object bufr from this object, and read the data from the bufr to get the resource file specified by the url.
If you want to be a friend of app, you can directly call parseHtml method, put the acquired data in the list, and perform a wave of "fierce as tiger" operations.