Android为TV端助力 比较完善json请求格式

public static String getHttpText(String url) {
if (MyApplication.FOR_DEBUG) {
Log.i(TAG, "[getHttpText1]" + url);
}
Log.i(TAG, "[getHttpText2]" + url);
if (url == null || url.equals(""))
return null;

StringBuilder builder = new StringBuilder();
InputStreamReader isReader = null;
HttpURLConnection conn = null;
try {
URL u = new URL(url);
conn = (HttpURLConnection) u.openConnection();
conn.setConnectTimeout(TIMEOUT);
if (conn == null || conn.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
conn.connect();
isReader = new InputStreamReader(conn.getInputStream());
BufferedReader reader = new BufferedReader(isReader);
String buffer;
while ((buffer = reader.readLine()) != null) {
builder.append(buffer);
}
reader.close();
return builder.toString();
} catch (Exception e) {
Log.e(TAG, "getHttpText error: " + e.getMessage());
} finally {
if (isReader != null) {
try {
isReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (conn != null) {
conn.disconnect();
}
}
return null;
}

上面是json的请求方式,参数只需要传一个对应的服务器地址就行,下面是解析格式

String json = HttpUtils.getHttpText(
Configs.getServerAddress(context)
+ "/api.php/Message/getMessage"
+ Configs.getRoomInfo(context));
if (json == null || json.equals(""))
continue;

try {
JSONObject root = new JSONObject(json);
if (root.getInt("status") != 0)
return;

boolean gotMessage = false;
JSONArray ja = root.getJSONArray("messageList");
int len = ja.length();
long now = System.currentTimeMillis();
for (int i = 0; i < len; i++) {
JSONObject jo = ja.getJSONObject(i);
long deadline = jo.getLong("finish_time") * 1000;
if (deadline <= now) continue;
MarqueeContent content = new MarqueeContent();
content.id = mMarqueeId++;
content.deadline = deadline;
content.text = jo.getString("content");
mMarqueeList.add(content);
gotMessage = true;
}
if (gotMessage) {
context.sendBroadcast(new Intent(MarqueeView.GOT_MARQUEE_ACTION));
}
return;
} catch (JSONException e) {
e.printStackTrace();
}

原文地址:https://www.cnblogs.com/xiaoxiaing/p/5404981.html