客户端 HttpURLConnection session不会丢失

 HttpURLConnection交互过程中需要服务器端保存session时候需要客户端提交sessionid上来所以,服务器有sessionid下来就要存储起来,每次都要上传上去,服务器端sessionid才不会丢失。

public static String doPost(String reqUrl, String parameters,
            String recvEncoding) {
        System.out.println("request:" + parameters);

        HttpURLConnection url_con = null;
        String responseContent = null;
        if (recvEncoding.isEmpty() || recvEncoding == null) {
            recvEncoding = "utf-8";
        }
        try {
            StringBuffer params = new StringBuffer();

  //中文乱码问题 参数必须进行中文编码 步骤1下面还有一个
            params.append("p=" + URLEncoder.encode(parameters, "utf-8"));

            URL url = new URL(reqUrl);

            // ****************************
            url_con = (HttpURLConnection) url.openConnection();
            Object objsid = ActionContext.getContext().getSession().get("sid");

            //判断是否有sessionid;
            if (objsid != null) {
                url_con.setRequestProperty("Cookie", objsid.toString());
            }

            url_con.setRequestMethod("POST");
            url_con.setConnectTimeout(500000);// (单位:毫秒)jdk 1.5换成这个,连接超时
            url_con.setReadTimeout(500000);// (单位:毫秒)jdk 1.5换成这个,读操作超时

            url_con.setDoOutput(true);

            byte[] byteParams = params.toString().getBytes();
//这里getBytes也要进行编码,这样才能保证参数能够传到服务器端不是乱码
            url_con.getOutputStream().write(parameters.getBytes("utf-8"));

            url_con.getOutputStream().flush();
            url_con.getOutputStream().close();

            // System.out.println(url_con.getResponseCode());

            InputStream in = url_con.getInputStream();
            String cookieVal = url_con.getHeaderField("Set-Cookie");

            if (cookieVal != null) {
                //存储sessionid;
                String sid = cookieVal.substring(0, cookieVal.indexOf(";"));
                if (sid != null && !sid.isEmpty()) {
                    ActionContext.getContext().getSession().put("sid", sid);
                }
            }

            BufferedReader rd = new BufferedReader(new InputStreamReader(in,
                    recvEncoding));
            String tempLine = rd.readLine();
            StringBuffer tempStr = new StringBuffer();
            String crlf = System.getProperty("line.separator");
            while (tempLine != null) {
                tempStr.append(tempLine);
                tempStr.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = tempStr.toString();
            rd.close();
            in.close();
        } catch (IOException e) {
            // logger.error("网络故障", e);
        } finally {
            if (url_con != null) {
                url_con.disconnect();
            }
        }
        System.out.println("Response:"+responseContent);
        return responseContent;
    }

posted on 2011-07-18 14:40  小小博客小小员  阅读(1986)  评论(0编辑  收藏  举报

导航