解析JSON

public class GetJson extends Thread {

private Handler handler;

private String url;

public GetJson(String url, Handler handler) {

this.url = url;

this.handler = handler;

}

@Override

public void run() {

super.run();

String json = getString();

Message me = new Message();

me.what = 0;

me.obj = json;

handler.sendMessage(me);

}

public String getString() {

try {

URL u = new URL(url);

HttpURLConnection connection = (HttpURLConnection) u.openConnection();

connection.setRequestMethod("GET");

connection.setConnectTimeout(5000);

if (connection.getResponseCode() == 200) {

InputStream inputStream = connection.getInputStream();

ByteArrayOutputStream output = new ByteArrayOutputStream();

int len = 0;

byte[] by = new byte[1024];

while ((len = inputStream.read(by)) != -1) {

output.write(by, 0, len);

}

return output.toString("utf-8");

}

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

}

你可能感兴趣的:(解析JSON)