JSON response and converting it to a JSON object -
i have piece of sample code request data website , response turns out gibberish.
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 input stream json bufferedreader br = new bufferedreader(new inputstreamreader((conn.getinputstream()))); string output; system.out.println("output server .... \n"); while ((output = br.readline()) != null) { system.out.println(output); } conn.disconnect(); } catch (malformedurlexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } }
}
how convert inputstream readable json object. found few questions have response , trying parse.
the first problem code server g'zipping response data, aren't handling. can verify retrieving data via browser , looking @ response headers:
http/1.1 200 ok
date: fri, 10 may 2013 16:03:45 gmt
server: apache/2.2.17 (unix) php/5.3.6
x-powered-by: php/5.3.6
vary: accept-encoding
content-encoding: gzip
keep-alive: timeout=5, max=100
connection: keep-alive
transfer-encoding: chunked
content-type: application/json
thats why output looks 'gibberish'. fix this, chain gzipinputstream
on top of url connections output stream.
// convert input stream 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()))); }
the second issue data returned in jsonp format (json wrapped in callback function, callback_function_name(json);
). need extract before parsing:
// retrieve data server string output = null; final stringbuffer buffer = new stringbuffer(16384); while ((output = br.readline()) != null) { buffer.append(output); } conn.disconnect(); // extract json jsonp envelope string jsonp = buffer.tostring(); string json = jsonp.substring(jsonp.indexof("(") + 1, jsonp.lastindexof(")")); system.out.println("output server"); system.out.println(json);
so thats it, have desired data server. @ point can use standard json library parse it. example, using gson:
final jsonelement element = new jsonparser().parse(json);
Comments
Post a Comment