解决方案 »

  1.   

    自己保存下session id,然后每次openConnection之后再把session id手动加上。
    如果你不希望session过期,在服务器端把session时间设置长点儿,或者干脆用cookie。
    貌似在app设计里面,用token(OAuth)的方式更常见一点儿,而不是session
      

  2.   

    /**
     * 根据url获得页面源码, 调用web接口
     * 
     * @param url
     *            访问地址, 必备参数
     * @param method
     *            请求方式post还是get, 默认get
     * @param params
     *            参数列表 post必备, 比如:"name=张三&age=18"
     * @param sessionInfo
     *            可以保持session, 默认不保持
     * @param encoding
     *            编码格式, 默认UTF_8
     * @param isLine
     *            得到的源码是否换行, 默认false
     * @return
     */
    public String requestUrl(String url, String method, String params, String sessionInfo, String encoding,
    boolean isLine) throws Exception {
    if (!isNet()) {
    throw new RuntimeException(AbstractActivity.NET_ERR_MSG + "\t" + url);
    }
    if (!Container.pingTck && !isMustRequest) {
    throw new RuntimeException(AbstractActivity.OP_ERROR_MSG + "\t" + url);
    }
    Log.e(Domain.TAG_NAME, "调用web接口:" + url);
    if (!isNet()) {
    throw new Exception(AbstractActivity.NET_ERR_MSG);
    }
    encoding = (ToolUtil.get().isBlank(encoding) ? HTTP.UTF_8 : encoding);
    method = (ToolUtil.get().isBlank(method) ? Domain.REQUEST_GET : method.toUpperCase());
    String mathStr = "platform=ANDROID,TCK," + SettingService.get().getString(SettingService.MOBILE_CODE)
    + "&mathRandom=" + Math.random();
    if (method.equals(Domain.REQUEST_GET)) {
    url += (url.indexOf("?") != -1 ? "&" : "?") + mathStr;
    }
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    if (!ToolUtil.get().isBlank(sessionInfo)) {
    conn.setRequestProperty("Cookie", sessionInfo);
    }
    conn.setRequestMethod(method);
    if (requestTime > 0) {
    conn.setConnectTimeout(isWifi() ? requestTime : requestTime * 3);
    conn.setReadTimeout(isWifi() ? requestTime : requestTime * 3);
    }
    if (method.equals(Domain.REQUEST_POST)) {
    conn.setDoOutput(true);
    OutputStream output = conn.getOutputStream();
    output.write((ToolUtil.get().isBlank(params) ? mathStr : params + "&" + mathStr).getBytes(encoding));
    output.flush();
    output.close();
    }
    String response = FileUtil.get().readFile(conn.getInputStream(), encoding, 1, isLine);
    conn.disconnect();
    return response;
    }
    String sessionInfo = "JSESSIONID=" + getSession().getId() + "; Path=" + getRequest().getContextPath();