Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> android 比較完善json請求格式,androidjson

android 比較完善json請求格式,androidjson

編輯:關於android開發

android 比較完善json請求格式,androidjson


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();
}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved