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

来源:互联网 发布:淘宝货号怎么填 编辑:程序博客网 时间:2024/06/01 08:49
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

0 0
原创粉丝点击