2013-05-10 2 views
0

웹 사이트에서 데이터를 요청할 수있는 샘플 코드가 있는데, 내가 얻은 응답은 횡설수설적인 것으로 판명되었습니다.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(); 
    } 
} 

}

어떻게 읽을 JSON 개체에의 InputStream를 변환 않습니다. 몇 가지 질문을 찾았지만 이미 응답을하고 분석하려고합니다.

+0

대신 conn.getOutputStream()을 사용 하시겠습니까? – softwarebear

답변

4

코드의 첫 번째 문제점은 서버가 처리하지 않는 응답 데이터를 g'zipping하고 있다는 것입니다. 당신은 쉽게 브라우저를 통해 데이터를 검색하고 응답 헤더를보고하여이를 확인할 수 있습니다

HTTP/1.1 200 OK
날짜 : 2013년 (금) 그리니치 표준시 16시 03분 45초
서버 5 월 10 : 아파치 /2.2.17 (유닉스) PHP/5.3.6
X-구동 - 기준 : PHP/5.3.6
비바리 : 수락 - 인코딩
콘텐츠 인코딩 : gzip을
연결 유지 : 제한 시간 = 5 , 최대 = 100
연결 : Keep-Alive,453,210 전송 - 인코딩 :
콘텐츠 형식을 청크 : 응용 프로그램/JSON

그게 당신의 출력은 '횡설수설'처럼 보이는 이유. 이 문제를 해결하려면 GZIPInputStream을 URL 연결 출력 스트림 위에 연결하기 만하면됩니다.

// convert the input stream to JSON 
BufferedReader br; 
if ("gzip".equalsIgnoreCase(conn.getContentEncoding())) { 
    br = new BufferedReader(new InputStreamReader(
      (new GZIPInputStream(conn.getInputStream())))); 
} else { 
    br = new BufferedReader(new InputStreamReader(
      (conn.getInputStream()))); 
} 

두 번째 문제는 리턴 데이터 (JSON이 콜백 함수 callback_function_name(JSON); 같은 래핑) JSONP 포맷 사실 때문이다. 구문 분석하기 전에 추출해야합니다.

// Retrieve data from server 
String output = null; 
final StringBuffer buffer = new StringBuffer(16384); 
while ((output = br.readLine()) != null) { 
    buffer.append(output); 
} 
conn.disconnect(); 

// Extract JSON from the JSONP envelope 
String jsonp = buffer.toString(); 
String json = jsonp.substring(jsonp.indexOf("(") + 1, 
     jsonp.lastIndexOf(")")); 
System.out.println("Output from server"); 
System.out.println(json); 

이제는 서버에서 원하는 데이터를 얻었습니다. 이 시점에서 모든 표준 JSON 라이브러리를 사용하여 구문 분석 할 수 있습니다. 예를 들어, GSON :

final JSONElement element = new JSONParser().parse(json); 
+0

정말 고맙습니다. GZIP 인코딩에 대해 몰랐습니다. 가능하다면 +100을 입력하십시오. 다시 한 번 감사드립니다. – jonleech

관련 문제