zoukankan      html  css  js  c++  java
  • 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();
    }

  • 相关阅读:
    ASP.NET MVC之从控制器传递数据到视图四种方式
    MVC发布到IIS,出现HTTP 错误 404.0
    超详细MySQL安装及基本使用教程
    node.js中使用node-xlsx插件生成excel数据并导出
    jquery给一组radio赋值和取值
    node.js生成excel下载各种方法分析对比--附excel-export方法
    JS中substr和substring的区别
    jq触发a标签的href跳转
    jq中跳出方法、for循环和each循环
    IIS应用程序池频繁崩溃的问题
  • 原文地址:https://www.cnblogs.com/xiaoxiaing/p/5404981.html
Copyright © 2011-2022 走看看