我有一段示例代碼來請求來自網站的數據,而我得到的響應原來是亂碼。JSON響應並將其轉換爲JSON對象
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientGet
{
public static void main(String[] args)
{
try
{
URL url = new URL("http://fids.changiairport.com/webfids/fidsp/get_flightinfo_cache.php?d=0&type=pa&lang=en");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200)
{
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
System.out.println("the connection content type : " + conn.getContentType());
// convert the input stream to JSON
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null)
{
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
如何InputStream的轉換成可讀的JSON對象。發現了幾個問題,但他們已經有了答案並試圖解析。
是否要conn.getOutputStream()來代替? – softwarebear 2013-05-10 09:13:32