有关httpClient获取sessionID的问题

qq_33550982 2016-04-12 05:28:58

public static void main(String[] args) {

HttpClient h = new HttpClient();
String sessionID = "";
try {
GetMethod get = new GetMethod("http://shop.gkyc.cn/login.jsp");
h.executeMethod(get);
Cookie[] cookie = h.getState().getCookies();
for(int i =0;i<cookie.length;i++){
if(cookie[i].getName().equals("JSESSIONID")){
sessionID = cookie[i].getValue();
System.out.println("第一次:::::::::::"+sessionID);
}
}
File f1 = new File("code1.png");
get = new GetMethod( "http://shop.gkyc.cn/vcodeimg.jsp" );
h.executeMethod(get);
InputStream in = get.getResponseBodyAsStream();
FileOutputStream out = new FileOutputStream(f1);
byte[] b = new byte[1024];
int len = 0;
while((len=in.read(b))!= -1){
out.write(b,0,len);
}

cookie = h.getState().getCookies();
for(int i =0;i<cookie.length;i++){
if(cookie[i].getName().equals("JSESSIONID")){
sessionID = cookie[i].getValue();
System.out.println("第二次:::::::::::"+sessionID);
}
}
System.out.println("开始调用uu打码:"+
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
boolean status=UUAPI.checkAPI(); //校验API,必须调用一次,校验失败,打码不成功
if(!status){
System.out.print("API文件校验失败,无法使用打码服务");
return;
}
String veridCode=UUAPI.easyDecaptcha("code1.png", 8002)[1];
System.out.println("uu打码成功("+veridCode+"):"+
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));



PostMethod post = new PostMethod("http://shop.gkyc.cn/login.jsp");

post.addParameter("userName", "wjszztrqyf");
post.addParameter("userPass", "wjszztrqyf");
post.addParameter("vcode", veridCode);
post.addParameter("loginBtn", "");

h.executeMethod(post);
cookie = h.getState().getCookies();
for(int i =0;i<cookie.length;i++){
if(cookie[i].getName().equals("JSESSIONID")){
sessionID = cookie[i].getValue();
System.out.println("第三次:::::::::::"+sessionID);
}
}

get = new GetMethod("http://shop.gkyc.cn/header.jsp");
/*if(sessionID!=null&&!sessionID.equals("")){
get.addRequestHeader("Cookie","JSESSIONID="+sessionID);
}*/
h.executeMethod(get);
cookie = h.getState().getCookies();
for(int i =0;i<cookie.length;i++){
if(cookie[i].getName().equals("JSESSIONID")){
sessionID = cookie[i].getValue();
System.out.println("第四次:::::::::::"+sessionID);
}
}
String response = get.getResponseBodyAsString();
//System.out.println(response);

if(response.contains("退出")){
System.out.println("OK");
}else{
System.out.println("false");
}

} catch (Exception e) {
e.printStackTrace();
}

}


控制台打印出来的sessionID 若登录成功 第2,3,4次的sessionID是一样的
为什么第一次get请求时 sessionID与后面几次的不同 都是同一个httpclient对象啊?
为什么第3次post请求的sessionID与第二次的相同啊
求告知啊 这httpClient是如何保持sessionID的
...全文
628 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
z905799779 2017-03-19
  • 打赏
  • 举报
回复
请问您的问题解决了吗
压缩包中含有多个文档,从了解httpclient到应用。 httpClient 1httpClint 1.1简介 HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。 下载地址:  http://hc.apache.org/downloads.cgi 1.2特性 1. 基于标准、纯净的java语言。实现了Http1.0和Http1.1 2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。 3. 支持HTTPS协议。 4. 通过Http代理建立透明的连接。 5. 利用CONNECT方法通过Http代理建立隧道的https连接。 6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。 7. 插件式的自定义认证方案。 8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。 9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。 10. 自动处理Set-Cookie中的Cookie。 11. 插件式的自定义Cookie策略。 12. Request的输出流可以避免流中内容直接缓冲到socket服务器。 13. Response的输入流可以有效的从socket服务器直接读取相应内容。 14. 在http1.0和http1.1中利用KeepAlive保持持久连接。 15. 直接获取服务器发送的response code和 headers。 16. 设置连接超时的能力。 17. 实验性的支持http1.1 response caching。 18. 源代码基于Apache License 可免费获取。 1.3版本 org.apache.http.impl.client.HttpClients 与 org.apache.commons.httpclient.HttpClient目前后者已被废弃,apache已不再支持。 一般而言,使用HttpClient均需导入httpclient.jar与httpclient-core.jar2个包。 1.4使用方法与步骤 开发环境:需要 使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。 1.创建HttpClient对象。 HttpClient client = new HttpClient(); 2.创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。 //使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的 http换成https HttpMethod method = new GetMethod("http://www.baidu.com"); //使用POST方法 HttpMethod method = new PostMethod("http://java.sun.com";); 3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。 3.调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。 client.executeMethod(method); 5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。 6. 释放连接。无论执行方法是否成功,都必须释放连接 //打印服务器返回的状态 System.out.println(method.getStatusLine()); //打印返回的信息 System.out.println(method.getResponseBodyAsString(
package windows; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Vector; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.params.ClientPNames; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; /** * 核心功能封装类 * @author 冯晋强 * */ public class TmoocOperate { static String sessionid; static CloseableHttpResponse response = null; static CloseableHttpClient httpclient = null; //静态块 static{ // 创建提交数据对象 httpclient = HttpClients.createDefault(); } /** * 处理在线疑答贴子列表源码数据 * @author 刑保政 */ public static String[][] splist(String Str) { Str = Str.substring(Str.lastIndexOf("
    ") + 4, Str.lastIndexOf("
")).replaceAll("\\s", ""); String[] lis = Str.split("");// 所有记录的数组 String[] jilu = null;// 单条记录的数组 String[][] allMsg = new String[lis.length - 1][4]; // 创建一个二维数组保存处理后的数据,其中每个一维数组中包含一个记录,每个二维数组中包含每条数据的信息 // allMsg[i][0]:标题; allMsg[i][1]:时间 allMsg[2]:处理状态 for (int i = 0; i < lis.length - 1; i++) {// 遍历所有记录,取出每一条记录 String ss = lis[i];// 取出每一条记录 jilu = ss.split("(
|)"); // 每条记录分割成3部分 jilu[0]:标题 jilu[2]:时间 jilu[3]:处理状态 for (int j = 0; j < jilu.length; j++) {// 由于数据中还含有部分额外代码,遍历所有记录筛选数据 String msg = jilu[j];// 单条记录中的每一个数据 System.out.println(msg); msg = msg.substring(msg.lastIndexOf(">") + 1, msg.length()); String uid = jilu[0].substring(jilu[0].lastIndexOf("(") + 1, jilu[0].lastIndexOf(")")); allMsg[i][j] = msg; allMsg[i][3] = uid; } } return allMsg; } /** * 处理在线疑答帖子内容源码数据 * @author 刑保政 */ public static String[] splist1(String all) { String queStr = all.substring(all.indexOf("
获取含有问题标题的内容 // System.out.println(queStr);//测试标题部分字符串 String[] queArr = queStr.split("()"); for(int i=0;i")+1, msg.length()); if(i == 5){ msg = msg.substring(msg.indexOf(":")+1).trim(); } queArr[i] = msg; } String[] que = new String[4];//保存最终标题内容的数组 que[0] = queArr[1]; que[1] = queArr[3]; que[2] = queArr[4]; que[3] = queArr[5]; for(int i=0;i<2;i++){ que[i] = que[i].replaceAll("<","<"); que[i] = que[i].replaceAll(">",">"); que[i] = que[i].replaceAll(" "," "); que[i] = que[i].replaceAll("&","&"); que[i] = que[i].replaceAll(""","\""); que[i] = que[i].replaceAll("©","@"); que[i] = que[i].replaceAll("®","商标"); } return que; } // 回复帖子方法包 public static boolean SetTitle1(String message,String uid) { try { // url提交地址 HttpPost httpPost = new HttpPost("http://tts8.tmooc.cn/onlinefaq/anwser"); // 组合数据包 List nvps = new ArrayList(); nvps.add(new BasicNameValuePair("questionId", uid)); nvps.add(new BasicNameValuePair("context", message)); // 设置数据包 httpPost.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8)); // 提交数据包 response = httpclient.execute(httpPost); // 读取返回数据信息 String str = EntityUtils.toString(response.getEntity()); System.out.println(str); if(str.indexOf("true")!=-1){ return true; }else{ return false; } } catch (ClientProtocolException e) { System.out.println("数据包提交失败"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } // 发送帖子方法包 public static boolean SetTitle(String tilte, String message) { try { // url提交地址 HttpPost httpPost = new HttpPost("http://tts8.tmooc.cn/onlinefaq/add"); // 组合数据包 List nvps = new ArrayList(); nvps.add(new BasicNameValuePair("title", tilte)); nvps.add(new BasicNameValuePair("context", message)); // 设置数据包 httpPost.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8)); // 提交数据包 response = httpclient.execute(httpPost); // 读取返回数据信息 String str = EntityUtils.toString(response.getEntity()); System.out.println(str); if(str.indexOf("true")!=-1){ return true; }else{ return false; } } catch (ClientProtocolException e) { System.out.println("数据包提交失败"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } /** * * @author 刑保政 */ public static Vector> getAite(Vector> vvs){ /** 保存所有姓名的集合,因为回帖人中有重复数据,所以这里用Set去除重复 */ Set usersSet = new HashSet(); /** 保存所有回帖内容的集合 */ List texts = new ArrayList(); /* 遍历回帖集合,分别取出每一条记录中的回帖人和回帖内容,并添加到 * 对应的集合中,方便下一步遍历筛选 */ for(int i=0;i v = vvs.get(i); String user = v.get(1); String text = v.get(3); usersSet.add(user); texts.add(text); } // System.out.println(users);//测试回帖人集合 // System.out.println(texts);//测试回帖内容集合 String[] users = new String[usersSet.size()]; usersSet.toArray(users);//将usersSet回帖人集合转为数组方便遍历 // System.out.println(Arrays.toString(users));//测试回帖人数组 /* 遍历回帖人数组,取出每一个回帖人, * 遍历每一条回帖内容,判断内容是否以@+回帖人开头,(当前设置@只能在开头有用,中间的不予考虑) * 若是则提取该回帖人并添加到当前楼层集合中 */ for(int i=0;i> getAnswer(String all){ all = all.substring(all.indexOf("
> vvs = new Vector>();//创建二维集合保存信息 /* * 遍历回帖集合,取出每一条回帖记录,分割成一组回帖信息元素, * 进行处理后添加进二维集合 */ for(int i = 1;i|)"); vvs.add(new Vector()); vvs.get(i-1).add(i + "");//楼层数 for(int j=0;j")+1,msg.length()).trim(); if(j == 1){//对时间单独进行处理一下 msg = msg.substring(msg.indexOf("(")+1,msg.length()-1).trim(); } vvs.get(i-1).add(msg);//添加进二维集合 } } vvs = getAite(vvs); return vvs; } // 读取在线疑答帖子内容源码数据 public static String Get_title(String uid) { try { // url提交地址 HttpGet httpGet = new HttpGet("http://tts8.tmooc.cn/onlinefaq/detail/"+ uid); // 提交数据包 response = httpclient.execute(httpGet); // 取出cookie System.out.println(response.getFirstHeader("Cookie")); // 读取返回数据信息 String str = EntityUtils.toString(response.getEntity()); return str; } catch (ClientProtocolException e) { System.out.println("数据包提交失败"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } // 读取在线疑答帖子列表源码数据 public static String Get_tilte() { try { // url提交地址 HttpGet httpGet = new HttpGet("http://tts8.tmooc.cn/onlinefaq/questionList"); // 提交数据包 response = httpclient.execute(httpGet); System.out.println("第七次请求成功"); // 读取返回数据信息 String str = EntityUtils.toString(response.getEntity()); return str; } catch (ClientProtocolException e) { System.out.println("数据包提交失败"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } // 初始化登陆,判断是否需要登陆验证码 暂时未完善 public static void GetCode(String user) { CloseableHttpClient httpclient = null; CloseableHttpResponse response2 = null; try { // url提交地址 HttpPost httpPost = new HttpPost("http://tmooc.cn/login/loginTimes"); // 组合数据包 List nvps = new ArrayList(); nvps.add(new BasicNameValuePair("login_name", user)); // 设置数据包 httpPost.setEntity(new UrlEncodedFormEntity(nvps)); // 创建提交数据对象 httpclient = HttpClients.createDefault(); // 提交数据包 response2 = httpclient.execute(httpPost); // 读取返回数据信息 String str = EntityUtils.toString(response2.getEntity()); System.out.println(str); TmoocOperate.SetTitle("今天的表示没怎么听懂", "你们呢。。。"); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { response2.close(); httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } // 登陆Tmooc方法 public static boolean Tmooc_Login(String user, String pass) { try { // url提交地址 HttpPost httpPost = new HttpPost("http://tmooc.cn/login"); // 组合数据包 List nvps = new ArrayList(); nvps.add(new BasicNameValuePair("login_name", user)); nvps.add(new BasicNameValuePair("password", Login_MD5(pass).toLowerCase())); nvps.add(new BasicNameValuePair("type", "P")); nvps.add(new BasicNameValuePair("uuid","E1CC4286A419C899CCBF6A04E5A1CF02")); // 设置数据包 httpPost.setEntity(new UrlEncodedFormEntity(nvps)); // 提交数据包 response = httpclient.execute(httpPost); // 读取返回数据信息 String str = EntityUtils.toString(response.getEntity()); //判断是否登陆成功 if (str.indexOf(user) != -1) { sessionid = str.substring(14, str.indexOf("|P#")); // 取出cookie方法 这里用不到 //Cookie = response2.getFirstHeader("Set-Cookie").toString(); // url提交地址 HttpGet httpGet = new HttpGet("http://tmooc.cn/login/hadlogin/"+ sessionid); // 提交数据包 response = httpclient.execute(httpGet); // url提交地址 httpGet = new HttpGet("http://tts8.tmooc.cn/user/myTTS?sessionId=" + sessionid + "&date="); // 提交数据包 response = httpclient.execute(httpGet); return true; } } catch (UnsupportedEncodingException e) { System.out.println("设置数据包出错"); e.printStackTrace(); } catch (ClientProtocolException e) { System.out.println("提交数据异常"); e.printStackTrace(); } catch (IOException e) { System.out.println("其他错误"); e.printStackTrace(); } return false; } //utf-8编码 public static String bm_utf8(String Str){ String bmjg = null; try { bmjg = URLEncoder.encode(Str, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return bmjg; } // 登陆tmooc时md5加密方法 public final static String Login_MD5(String s) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; try { byte[] btInput = s.getBytes(); // 获得MD5摘要算法的 MessageDigest 对象 MessageDigest mdInst = MessageDigest.getInstance("MD5"); // 使用指定的字节更新摘要 mdInst.update(btInput); // 获得密文 byte[] md = mdInst.digest(); // 把密文转换成十六进制的字符串形式 int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { e.printStackTrace(); return null; } } }

39,084

社区成员

发帖
与我相关
我的任务
社区描述
HTML5是构建Web内容的一种语言描述方式。HTML5是互联网的下一代标准,是构建以及呈现互联网内容的一种语言方式.被认为是互联网的核心技术之一。
社区管理员
  • HTML5社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧