2018年11月13日 星期二
java 從網址取得 json data 並解析
package test_4;
import org.json.*;
import java.net.*;
import java.io.*;
import static java.lang.System.out;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author xman
*/
public class T_1 {
public static String getURLContent(String urlPath) throws MalformedURLException, IOException {
String content = "";
HttpURLConnection connection = null;
BufferedReader in;
URL url = null;
url = new URL(urlPath);
URLConnection urlConnection = url.openConnection();
if (urlConnection instanceof HttpURLConnection) {
connection = (HttpURLConnection) urlConnection;
} else {
System.out.println("请输入 URL 地址");
return content;
}
in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String current;
while ((current = in.readLine()) != null) {
content += current;
}
return content;
}
public static void main(String[] args) throws Exception {
String htmlContent = getURLContent("http://localhost:8081/test_1/JSON/t_1.php");
// out.println(htmlContent);
JSONObject j;
j = new JSONObject(htmlContent);
Iterator<String> it = j.keys();;
while (it.hasNext()) {
String key = it.next();
Object o_1 = j.get(key);
out.printf("(%s)=>(%s)\n", key, o_1.toString());
}
}
}