使用URLHttpConnection访问中session的问题解决方案

package com.custom.test;


import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;


/***
 * 2015-1-29日20:08使用URLHttpConnection访问中session的问题解决方案
 * 
 */
public class PostTest {
static long sessionCreateTime = 0l;


public synchronized static void createSession() {
if (null == SessionTest.sessionid || "".equals(SessionTest.sessionid)) {
SessionTest.sessionid = getSessionId();
System.out.println("session创建!");
sessionCreateTime = new Date().getTime();
}


// 20分钟后更换session
long nowTime = new Date().getTime();
int min = (int) ((nowTime - sessionCreateTime) / (1000 * 60));
if (min >= 15) {
SessionTest.sessionid = getSessionId();
System.out.println("session重新创建!");
sessionCreateTime = new Date().getTime();
} else {
sessionCreateTime = new Date().getTime();
}


}


private static String getSessionId() {
URL _url;
String sessionid = null;
try {
_url = new URL("http://192.168.0.161:8080/kdb_server/MyJsp.jsp");


HttpURLConnection con = (HttpURLConnection) _url.openConnection();


// 取得sessionid.
String cookieval = con.getHeaderField("Set-Cookie");
System.out.println("cookieval===" + cookieval);
if (cookieval != null) {
sessionid = cookieval.substring(0, cookieval.indexOf(";"));
}
con.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return sessionid;
}


public void testSavePs() {
try {
URL url = new URL(
"http://192.168.0.161:8080/kdb_server/cus/submitpass.action");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();


createSession();
if (null != SessionTest.sessionid
|| !"".equals(SessionTest.sessionid)) {
System.out.println(("App.sessionId=" + SessionTest.sessionid));
conn.setRequestProperty("Cookie", SessionTest.sessionid);
}
conn.setRequestMethod("POST");// 提交模式
conn.setDoOutput(true);// 是否输入参数


StringBuffer params = new StringBuffer();
// 表单参数与get形式一样
params.append("USER_TEL").append("=").append("18791473412");//
byte[] bypes = params.toString().getBytes();
conn.getOutputStream().write(bypes);// 输入参数
InputStream inStream = conn.getInputStream();
System.out.println(new String(StreamTool.readInputStream(inStream),
"gbk"));
} catch (Exception e) {
e.printStackTrace();
}
}


public void sendEms() throws Exception {
URL url = new URL(
"http://192.168.0.161:8080/kdb_server/cus/getcode.action");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();


createSession();
if (null != SessionTest.sessionid || !"".equals(SessionTest.sessionid)) {
// Log.e(App.Log.app_name,"App.sessionId="+TestSession.sessionid);
System.out.println(("App.sessionId=" + SessionTest.sessionid));
conn.setRequestProperty("Cookie", SessionTest.sessionid);
}


conn.setRequestMethod("POST");// 提交模式
// conn.setConnectTimeout(10000);//连接超时 单位毫秒
// conn.setReadTimeout(2000);//读取超时 单位毫秒
conn.setDoOutput(true);// 是否输入参数


StringBuffer params = new StringBuffer();
// 表单参数与get形式一样
params.append("USER_TEL").append("=").append("18791473412");// .append("&").append("btnSearch").append("=").append(btnSearch);
byte[] bypes = params.toString().getBytes();
conn.getOutputStream().write(bypes);// 输入参数
InputStream inStream = conn.getInputStream();
System.out.println(new String(StreamTool.readInputStream(inStream),
"gbk"));


testSavePs();
}


public static void main(String[] args) {
try {
new PostTest().sendEms();
} catch (Exception e) {
e.printStackTrace();
}
}

}




package com.custom.test;


import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;


public class SessionTest {
public static String sessionid;
static long sessionCreateTime = 0l;


public synchronized static void createSession() {
if (null == SessionTest.sessionid || "".equals(SessionTest.sessionid)) {
SessionTest.sessionid = getSessionId();
System.out.println("session创建!");
sessionCreateTime = new Date().getTime();
}


// 20分钟后更换session
long nowTime = new Date().getTime();
int min = (int) ((nowTime - sessionCreateTime) / (1000 * 60));
if (min >= 15) {
SessionTest.sessionid = getSessionId();
System.out.println("session重新创建!");
sessionCreateTime = new Date().getTime();
} else {
sessionCreateTime = new Date().getTime();
}


}


private static String getSessionId() {
URL _url;
String sessionid = null;
try {
_url = new URL("http://192.168.0.161:8080/kdb_server/MyJsp.jsp");


HttpURLConnection con = (HttpURLConnection) _url.openConnection();


// 取得sessionid.
String cookieval = con.getHeaderField("Set-Cookie");
System.out.println("cookieval===" + cookieval);
if (cookieval != null) {
sessionid = cookieval.substring(0, cookieval.indexOf(";"));
}
con.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return sessionid;
}


public void postTest() {
String uriAPI = "http://192.168.0.161:8080/kdb_server/cus/getcode.action";
/* 建立HTTP Post连线 */
HttpPost httpRequest = new HttpPost(uriAPI);
createSession();
httpRequest.addHeader("Cookie", SessionTest.sessionid);
// Post运作传送变数必须用NameValuePair[]阵列储存
// 传参数 服务端获取的方法为request.getParameter("name")
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("USER_TEL", "1879147342"));
try {


// 发出HTTP request
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
// 取得HTTP response
HttpResponse httpResponse = new DefaultHttpClient()
.execute(httpRequest);


// 若状态码为200 ok
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 取出回应字串
// String
// strResult=EntityUtils.toString(httpResponse.getEntity());
// textView1.setText(strResult);
} else {
// textView1.setText("Error Response"+httpResponse.getStatusLine().toString());
}
} catch (Exception e) {
e.printStackTrace();
}
postTest2();
}


public void postTest2() {
String uriAPI = "http://192.168.0.161:8080/kdb_server/cus/submitpass.action";
/* 建立HTTP Post连线 */
HttpPost httpRequest = new HttpPost(uriAPI);
createSession();
httpRequest.addHeader("Cookie", SessionTest.sessionid);
// Post运作传送变数必须用NameValuePair[]阵列储存
// 传参数 服务端获取的方法为request.getParameter("name")
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("USER_TEL", "1879147342"));
try {


// 发出HTTP request
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
// 取得HTTP response
HttpResponse httpResponse = new DefaultHttpClient()
.execute(httpRequest);


// 若状态码为200 ok
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 取出回应字串
// String
// strResult=EntityUtils.toString(httpResponse.getEntity());
// textView1.setText(strResult);
} else {
// textView1.setText("Error Response"+httpResponse.getStatusLine().toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}


public static void main(String[] args) {
new SessionTest().postTest();
}
}




package com.custom.test;


import java.io.ByteArrayOutputStream;
import java.io.InputStream;


public class StreamTool {
    /**
     * 从输入流中读取数据
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len = inStream.read(buffer)) !=-1 ){
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();//网页的二进制数据
        outStream.close();
        inStream.close();
        return data;
    }
}



参考原文:http://bbs.9ria.com/thread-246113-1-1.html

package test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.Map; public class HttpTest { private HttpURLConnection hc = null; private static final String oneUrlString = "http://xxx.jsp"; private static final String twoUrlString = "http://xxx.action"; public String getSessionId() { String sessionId = ""; try { URL url = new URL(oneUrlString); hc = (HttpURLConnection) url.openConnection();//默认的用GET提交 hc.setDoOutput(true); hc.connect(); Map map = hc.getHeaderFields(); //得到Cookie的所有内容,包括SESSIONID,在进行下次提交的时候 直接把这个Cookie的值设到头里头就行了 //淡然只得到SESSIONID也很简单的 ,但是有时候Set-Cookie的值有几个的 List list = (List) map.get("Set-Cookie"); if(list.size() == 0||list == null) { return null; } StringBuilder builder = new StringBuilder(); for(String str : list) { sessionId = builder.append(str).toString(); } hc.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sessionId; } public String getResponseContext(String parameters) { String responseContext = ""; try { URL url = new URL(twoUrlString); hc = (HttpURLConnection) url.openConnection();//使用POST提交 hc.addRequestProperty("Cookie", getSessionId()); hc.setDoOutput(true); hc.connect(); OutputStream out = hc.getOutputStream(); //参数是a=""&b=""这样拼接的一个串 out.flush(); out.close(); out.write(parameters.getBytes(),0,parameters.getBytes().length); InputStream in = hc.getInputStream(); InputStreamReader reader = new InputStreamReader(in,"gb2312"); BufferedReader read = new BufferedReader(reader); StringBuilder builder = new StringBuilder(); String str = ""; while((str = read.readLine()) != null) { builder = builder.append(str); } read.close(); reader.close(); in.close(); hc.disconnect(); responseContext = builder.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return responseContext; } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值