httpClient 连接 https + 证书连接


httpClient 连接 https(证书连接+cookie更新+post自动跳转)


本文以获得验证码图片为例
这个是登陆页面:https://frontier.xian.12306.cn/gateway/hydzsw/Dzsw/login_bur.jsp
这个事登陆验证码:https://frontier.xian.12306.cn/gateway/hydzsw/Dzsw/security/jcaptcha.jpg
现在就以获得这个验证码图片为例
1.首先打开 https://frontier.xian.12306.cn/gateway/hydzsw/Dzsw/login_bur.jsp
(如果浏览器提示该证书,查看该证书,并将该证书导出为cer文件,如12306.cert
 提示:如果你的浏览器版本比较低,或代开该网站直接被拒,可能是该网站的证书已过期,
 如证书有效期是2011-1-1到2013-1-1,此时你可以讲自己电脑的系统时间改成该证书有效期范围内的任意一个时间就可以上网了)
2.将cer转换为keystore,方便用代码来加载该证书
 keytool -import -alias keystore12306 -file 12306.cer -keystore my.truststore  (如果自己配置tomcat支持https,方法如下文章:Tomcat配置HTTPS方式.txt,
 在该配置中需要先生产自己的keystore,然后在将该keystore转换为cert)
 
3.下面就可以将my.truststore 最为证书,用java代码来进行其他操作了
/*
本文所用开发工具
jak1.5.0_06
eclipse:ObjectWeb Lomboz
lib:
commons-codec-1.4.jar
commons-logging-1.1.jar
httpclient-4.0.3.jar
httpclient-cache-4.1.3.jar
httpcore-4.1.jar
httpmime-4.1.2.jar
*/
// lib 下载地址 http://download.csdn.net/detail/lanmo555/5033649

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
/**
 * 利用HttpClient,模拟https连接
 * 使用4.1版本
 * @since 2011.7.7
 */
public class cpdg{
 
 public static void main(String[] args) throws Exception {
 
  HttpClient httpclient = new DefaultHttpClient();
//  获得密匙库
  KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());
  FileInputStream instream = new FileInputStream(new File("D:/cpdg/my.truststore"));
  //密匙库的密码
  trustStore.load(instream, "123456".toCharArray());
  //注册密匙库
  SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
  //不校验域名
  socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  Scheme sch =new Scheme(  "https", socketFactory, 443);
  httpclient.getConnectionManager().getSchemeRegistry().register(sch);
  //获得HttpGet对象
  String urlJsp = "https://frontier.xian.12306.cn/gateway/hydzsw/Dzsw/login_bur.jsp";
  String urlJpg = "https://frontier.xian.12306.cn/gateway/hydzsw/Dzsw/security/jcaptcha.jpg";
  String url = "https://localhost:8443/tomcat.gif";
 
 
  HttpGet httpGet = null;
  httpGet = new HttpGet(urlJpg);
  //发送请求
  HttpResponse response = httpclient.execute(httpGet);
  InputStream is = response.getEntity().getContent();
  BufferedReader br = new BufferedReader(new InputStreamReader(is));
  //保存验证码图片
  String filename="d:/cpdg/jpg.gif";
  File storeFile = new File(filename); 
  FileOutputStream output=null;
  output = new FileOutputStream(storeFile);
  response.getEntity().writeTo(output);
  output.close();
 
  /*
  //输出返回的String
  InputStream is = response.getEntity().getContent();
  BufferedReader br = new BufferedReader(new InputStreamReader(is));
  String line = "";
  while((line = br.readLine())!=null){
   System.out.println(line);
  }
  */
 
  /*
  BufferedReader in = null;
  String keyStore = "d:/cpdg/my.keystore"; //证书的路径,pfx格式
  String trustStore = "d:/cpdg/my.truststore";//密钥库文件,jks格式
  String keyPass ="123456"; //pfx文件的密码
  String trustPass = "123456"; //jks文件的密码
  SSLContext sslContext = null;
  try {
   KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
   // 加载pfx文件      
   ks.load(new FileInputStream(keyStore), keyPass.toCharArray());
   KeyManagerFactory kmf = KeyManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
   kmf.init(ks, keyPass.toCharArray());
   KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
   //加载jks文件
   ts.load(new FileInputStream(trustStore), trustPass.toCharArray());
   TrustManager[] tm;
   TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
   tmf.init(ts);
   tm = tmf.getTrustManagers();
   sslContext = SSLContext.getInstance("SSL");
   sslContext.init(kmf.getKeyManagers(), tm, null);
  } catch (Exception e) {
   e.printStackTrace();
  }
     SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext);
     Scheme sch = new Scheme("https", socketFactory, 443);
     httpclient.getConnectionManager().getSchemeRegistry().register(sch);
     String queryUrl = "https://frontier.xian.12306.cn/gateway/hydzsw/Dzsw/security/jcaptcha.jpg";
     HttpPost httpPost = new HttpPost(queryUrl);
     HttpResponse httpResponse = httpclient.execute(httpPost);
     
  */
    }
}
 
Tomcat配置HTTPS方式.txt
简要记录主要步骤备忘
1、进入到jdk下的bin目录
2、输入如下指令
keytool -v -genkey -alias tomcat -keyalg RSA -keystore d:/tomcat.keystore  -validity 36500
附:
d:/tomcat.keystore是将生成的tomcat.keystore放到d盘根目录下。
"-validity 36500”含义是证书有效期,36500表示100年,默认值是90天
注意若要放到c盘,在win7系统下,需要以管理员身份进入到命令行中进行操作,否则是无法创建tomcat.keystore的。本例放到d盘下。
如何以管理员身份进入到命令行下呢?开始->搜索框中输入cmd->等待(注意不回车)->出现cmd.exe->右键“以管理员身份运行”即可。
3、输入keystore密码
密码任意,此处以123456为例,要记住这个密码,之后在进行server.xml配置时需要使用。
4、输入名字、组织单位、组织、市、省、国家等信息
注意事项:
A、Enter keystore password:此处需要输入大于6个字符的字符串
B、“What is your first and last name?”这是必填项,并且必须是TOMCAT部署主机的域名或者IP[如:gbcom.com 或者 10.1.25.251],就是你将来要在浏览器中输入的访问地址
C、“What is the name of your organizational unit?”、“What is the name of your organization?”、“What is the name of your City or Locality?”、“What is the name of your State or Province?”、“What is the two-letter country code for this unit?”可以按照需要填写也可以不填写直接回车,在系统询问“correct?”时,对照输入信息,如果符合要求则使用键盘输入字母“y”,否则输入“n”重新填写上面的信息
D、Enter key password for <tomcat>,这项较为重要,会在tomcat配置文件中使用,建议输入与keystore的密码一致,设置其它密码也可以
l  完成上述输入后,直接回车则在你在第二步中定义的位置找到生成的文件
5、输入之后会出现确认的提示
此时输入y,并回车。此时创建完成keystore。
进入到D盘根目录下可以看到已经生成的tomcat.xml
6、进入tomcat文件夹
找到conf目录下的sever.xml并进行编辑
7、编辑
  <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
     maxThreads="150" scheme="https" secure="true"
     clientAuth="false" keystoreFile="D:/AppServer/Tomcat/apache-tomcat-6.0.32/conf/tomcat.keystore"
     keystorePass="deleiguo" sslProtocol="TLS" />
注:
方框中的keystore的密码,就是刚才我们设置的“123456”.
编辑完成后关闭并保存sever.xml
8、Tomcat启动成功后,使用https://127.0.0.1:8443 访问页面
页面成功打开即tomcat下的https配置成功。
 
9、应用程序HTTP自动跳转到HTTPS
在应用程序中web.xml中加入:
<security-constraint>
       <web-resource-collection >
              <web-resource-name >SSL</web-resource-name>
              <url-pattern>/*</url-pattern>
       </web-resource-collection>
                            
       <user-data-constraint>
              <transport-guarantee>CONFIDENTIAL</transport-guarantee>
       </user-data-constraint>
</security-constraint>
 
10、生成安全证书文件
keytool -export -alias tomcat -file D:/file.cer -keystore d:/tomcat.keystore -validity 36500
然后输入d:/tomcat.keystore中的keystore密码
 
-file D:/file.cer 即为生成的cer文件,可直接点击安装
 
11、注意事项:
(1)    生成证书的时间,如果IE客户端所在机器的时间早于证书生效时间,或者晚于有效时间,IE会提示“该安全证书已到期或还未生效”
(2)    如果IE提示“安全证书上的名称无效或者与站点名称不匹配”,则是由生成证书时填写的服务器所在主机的域名“您的名字与姓氏是什么?”/“What is your first and last name?”不正确引起的
 
12、遗留问题:
(1)如果AC主机不能通过域名查找,必须使用IP,但是这个IP只有在配置后才能确定,这样证书就必须在AC确定IP地址后才能生成
(2)证书文件只能绑定一个IP地址,假设有10.1.25.250 和 192.168.1.250 两个IP地址,在证书生成文件时,如使用了10.1.25.250,通过IE就只能使用10.1.25.250 来访问AC-WEB,192.168.1.250是无法访问AC-WEB的。


/*
* 实现登陆https
* 1. 首先按如上的方法获得验证码,并从中获得cookie
* 2. 保存好该cookie,然后提交post
* 3. 如果页面时自动跳转的,你要用代码来实现跳转(header中的Location),而跳转的过程中需要更新cookie(从post返回的header中的 *     Set-Cookie获得)
*/


/*
URL:
https://frontier.xian.12306.cn/gateway/hydzsw/Dzsw/login_bur.jsp
user:3025725
pwd:11

https://frontier.xian.12306.cn/action/ResetPwdAction_initResPwnPage
gateway/hydzsw/Dzsw/j_spring_security_check
j_username
j_password
/gateway/hydzsw/Dzsw/security/jcaptcha.jpg

 113.201.60.195:443
https://frontier.xian.12306.cn/gateway/hydzsw/Dzsw/security/jcaptcha.jpg
function onImageClick(o) {
  o.src = "/gateway/hydzsw/Dzsw/security/jcaptcha.jpg?update=" + Math.random();
 }
*/
//code Test.java
package com.ipmotor.sm.db;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * 利用HttpClient,模拟https连接
 * 使用4.1版本
 * @since 2011.7.7
 */
public class Test{
   
    /**
     * 运行主方法
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
      //获得httpclient对象
      HttpClient httpclient = new DefaultHttpClient();
      //获得密匙库
      KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());
      FileInputStream instream = new FileInputStream(new File("D:/zzaa"));
      //密匙库的密码
      trustStore.load(instream, "123456".toCharArray());
      //注册密匙库
      SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
      //不校验域名
      socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      Scheme sch = new Scheme("https", 800, socketFactory);
      httpclient.getConnectionManager().getSchemeRegistry().register(sch);
      //获得HttpGet对象
      HttpGet httpGet = null;
      httpGet = new HttpGet("https://10.15.32.176:800/cgi-bin/service.cgi?session=caef0c3742c8f8ef4c98772e860c9fd2&rand=128&domain=sun.com&type=domain&cmd=disable");
      //发送请求
      HttpResponse response = httpclient.execute(httpGet);
      //输出返回值
      InputStream is = response.getEntity().getContent();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      String line = "";
      while((line = br.readLine())!=null){
          System.out.println(line);
      }
    }
}依赖的jar包
commons-codec-1.4.jar
commons-logging-1.1.1.jar
httpclient-4.1.1.jar
httpclient-cache-4.1.1.jar
httpcore-4.1.jar
httpmime-4.1.1.jar
 
// code  myhttpclient.java
package modules.myhttpclient;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class myhttpBean {
 public static String    mykeystore="D:/cpdg/my.truststore";
 public static List<Cookie>  cookies = null;
 public static String    sessionID = "";
 public static String    cookieString = "";
 public static HttpClient   httpclient=null;
 public static HttpPost   httppost = null;
 public static HttpGet    httpget = null;
 public static HttpResponse  response = null;
 
 public myhttpBean(){ }
 public static void main(String args[])
 throws Exception
 {
  System.out.println("test");
 // getGif();
 // getPage();
 
 }
 public static HttpClient setHttpsClient(HttpClient httpclient,int port)
 {
//  获得密匙库
  KeyStore trustStore = null;
  try
  {
   trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  }
  catch (KeyStoreException e)
  {
   e.printStackTrace();
  }
  FileInputStream instream = null;
  try
  {
   instream = new FileInputStream(new File(mykeystore));
  }
  catch (FileNotFoundException e1)
  {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  //密匙库的密码
  try
  {
   trustStore.load(instream, "123456".toCharArray());
  }
  catch (NoSuchAlgorithmException e)
  {
   e.printStackTrace();
  }
  catch (CertificateException e)
  {
   e.printStackTrace();
  }
  catch (IOException e)
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  //注册密匙库
  SSLSocketFactory socketFactory = null;
  try
  {
   socketFactory = new SSLSocketFactory(trustStore);
  }
  catch (KeyManagementException e)
  {
   e.printStackTrace();
  }
  catch (NoSuchAlgorithmException e)
  {
   e.printStackTrace();
  }
  catch (KeyStoreException e)
  {
   e.printStackTrace();
  }
  catch (UnrecoverableKeyException e)
  {
   e.printStackTrace();
  }
  //不校验域名
  socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  Scheme sch =new Scheme(  "https", socketFactory, port);
  httpclient.getConnectionManager().getSchemeRegistry().register(sch);
 
  return httpclient;
 }
 
 public static String getLoingHtml()
  throws IOException
 {
  String html="";
  System.out.println("********************************************************************************************");
  System.out.println("Function [getLoginHtml]!");
 
  String url = "https://frontier.xian.12306.cn/gateway/hydzsw/Dzsw/login_bur.jsp";
  HttpParams  params = new BasicHttpParams();
  HttpClientParams.setRedirecting(params, true);
  httpclient = new DefaultHttpClient(params);
  setHttpsClient(httpclient, 443);
  HttpGet httpGet = null;
  httpGet = new HttpGet(url);
  System.out.println("发送请求..Login Html.........");
  response = httpclient.execute(httpGet);
 
  cookies = ((AbstractHttpClient) httpclient).getCookieStore().getCookies();
  if (cookies.isEmpty()) {
   System.out.println("Cookies is empty!");
  } else {
   System.out.println("[ cookies ] = ");
   for (int i = 0; i < cookies.size(); i++) {
    sessionID += cookies.get(i).toString();
    System.out.println(cookies.get(i).toString());
   }
  }
 // sessionID = response.getFirstHeader("Set-Cookie").getValue();
  System.out.println("cookie[sessionID] = "+sessionID);

  InputStream is = response.getEntity().getContent();
  BufferedReader br = new BufferedReader(new InputStreamReader(is));
  return html;
 }
 
 public static String getGif(String gifPath, ServletContext sc,HttpSession session)
  throws IOException
 {
  System.out.println("********************************************************************************************");
  String realPath = sc.getRealPath("/");
  gifPath = realPath;
  System.out.println("Function [get gif for yzm]!\n RealPath:"+realPath);
 
  //获得HttpGet对象
  String url = "https://frontier.xian.12306.cn/gateway/hydzsw/Dzsw/security/jcaptcha.jpg?update="+Math.random();
  System.out.println("get gif  url:"+url);
 
  HttpParams  params = new BasicHttpParams();
 // HttpClientParams.setCookiePolicy(params, "http.protocol.cookie-policy");
 // params.setParameter("http.protocol.cookie-policy", CookiePolicy.RFC_2965);
  HttpClientParams.setRedirecting(params, true);
  httpclient = new DefaultHttpClient(params);
  setHttpsClient(httpclient, 443);
  HttpGet httpGet = null;
  httpGet = new HttpGet(url);
  httpGet.setHeader("Cookie", sessionID);
  System.out.println("发送请求..验证码............");
  httpclient.getParams().setParameter(
                ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);  //设置cookie的兼容性
  response = httpclient.execute(httpGet);
  
  cookies = ((AbstractHttpClient) httpclient).getCookieStore().getCookies();
  cookieString = "";
  if (cookies.isEmpty()) {
   System.out.println("Cookies is empty!");
  } else {
   System.out.println("[ cookies ] = ");
   for (int i = cookies.size()-1; i >=0 ; i--) {
    cookieString += " "+cookies.get(i).getName()+"="+ cookies.get(i).getValue()+";";
    System.out.println(cookies.get(i).toString());
   }
  }
  System.out.println("Cookie:" + cookieString);
  InputStream is = response.getEntity().getContent();
  BufferedReader br = new BufferedReader(new InputStreamReader(is));
 // gifPath = gifPath.replaceAll("\\\\", "/");
  double rand = Math.random()*1000000;
  String filename = "image/yzm/yzm" + Double.toString(rand)+".gif";
  String filePath = gifPath + filename;
  File storeFile = new File(filePath); 
  FileOutputStream output=null;
  output = new FileOutputStream(storeFile);
  response.getEntity().writeTo(output);
  output.close();
  System.out.println("Done! Saved to path: "+filePath);
  return  filename;
 }
 
 public static String Login(String userName, String password, String yzm)
 {
  System.out.println("********************************************************************************************");
  System.out.println("Function Login \n Cookie:"+cookieString);
 
  HttpParams  httpparams = new BasicHttpParams();
  HttpClientParams.setRedirecting(httpparams, true);
  httpclient =  new  DefaultHttpClient(httpparams);
  setHttpsClient(httpclient, 443);
  String posturl = "https://frontier.xian.12306.cn/gateway/hydzsw/Dzsw/j_spring_security_check";
  httppost = new HttpPost(posturl);
 
  System.out.println("[Login]= [userName:"+userName+"] [password:"+password + "] [yzm:"+yzm+"]");
 
  List<NameValuePair> params = new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("j_username", userName));
  params.add(new BasicNameValuePair("j_password", password));
  params.add(new BasicNameValuePair("j_captcha", yzm));
  params.add(new BasicNameValuePair("fromUrl", "/login_bur.jsp"));
  String strResult="";
  try {
   httppost.setHeader("Cookie",cookieString);
   httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
   HttpResponse httpResponse = httpclient.execute(httppost);
   if (httpResponse.getStatusLine().getStatusCode() == 302) {
    // 读返回数据
    strResult += "\n****************************************************************************\n";
    strResult += "Logining: ";
    strResult += EntityUtils.toString(httpResponse.getEntity());
    sessionID = httpResponse.getFirstHeader("Set-Cookie").getValue();
    String cookieName = sessionID.split("=")[0];
    cookieString = "";
    if(sessionID!="")
    {
     for (int i = cookies.size()-1; i >=0 ; i--) {
      if(cookies.get(i).getName().equals(cookieName))
       cookieString += " " + sessionID.split(";")[0]+";";
      else
       cookieString += " "+cookies.get(i).getName()+"="+cookies.get(i).getValue()+";";
     // ((AbstractHttpClient) httpclient).getCookieStore().addCookie(cookies.get(i));
     }
    }
    strResult += "new cookie:"+cookieString +"\n";
    String url = "";   //页面跳转
             Header locationHeader = httpResponse.getFirstHeader("Location");
             System.out.println("页面跳转="+locationHeader.getValue());
             if (locationHeader != null) {
                 url = locationHeader.getValue(); // 得到跳转href
                 httpget = new HttpGet("https://frontier.xian.12306.cn/" + url);
                 httpget.setHeader("Cookie", cookieString);
                
                 httpResponse = httpclient.execute(httpget);
                 strResult += "****************************************************************************\n";
     strResult += "登陆成功: \n";
     strResult += httpResponse.getStatusLine().toString() +"\n";
     strResult += EntityUtils.toString(httpResponse.getEntity());
    
             }

   } else {
    strResult = "Error Response: "
     + httpResponse.getStatusLine().toString() +"\n\n"+
     EntityUtils.toString(httpResponse.getEntity());
   }
  } catch (ClientProtocolException e) {
   strResult = e.getMessage().toString();
   e.printStackTrace();
  } catch (IOException e) {
   strResult = e.getMessage().toString();
   e.printStackTrace();
  } catch (Exception e) {
   strResult = e.getMessage().toString();
   e.printStackTrace();
  }
  System.out.println("strResult=\n" + strResult);
  return strResult;
 }
 
 public String cutPage(String html, String cookie, ServletContext sc, HttpSession session)
 throws Exception
 {
  System.out.println("cutPage"+html);
  System.out.println("***************************************************************");
  String outhtml=new String("<html>");
 
  html = html.replace("\"/lefu","\"http://www.sd.10086.cn/lefu");
 
  Document doc = Jsoup.parse(html);
  Element lhead = doc.getElementsByTag("head").first();
  outhtml += lhead;
  Element body = doc.getElementsByTag("body").first();
  String bodyonload  = body.attr("onload");
System.out.println("bodyonload: "+bodyonload);
  outhtml += "<body οnlοad=\""+bodyonload+"\" >";
  String[] s1 = bodyonload.split("'");
  String s2 = s1[s1.length-2].trim();
  Elements yzm = doc.select("input#yanzhengma");
     yzm.attr("onkeyup","");
     Elements code = doc.select("input#feeCode");
     code.attr("onkeyup","");
 
     Elements content = doc.select("div#content");
     content.attr("style","background:none;width:500;height:200");
    
     Elements main = doc.select("div.main");
     main.attr("style","width:200");
    
     Elements form = doc.select("form#frmM");
     outhtml += "<div align=\"center\">"+form;
    
  System.out.println(s2);
     if(s2!="" || s2.length()>0) {
      outhtml += "<script> ";
    //  outhtml += "var tab = document.getElementById(\"tab\");";
  //    outhtml += "var obj = tab.rows[2].cells[1];";
 //     outhtml += "obj.innerHTML = \"<span style=\"color:red\">"+s2+"</span>\";";
      int index = bodyonload.indexOf("lock");
      System.out.println("index of lock: "+index);
      if(index<0){
       outhtml += "javascript:history.go(-1);";
       outhtml += "alert(\""+s2+"\");";
      }
      outhtml += "</script>";
     }
     outhtml += "</div></body></html>";
    
  
    
     Document doc2 = Jsoup.parse(outhtml);
     Element table1 = doc2.getElementsByTag("table").first();
     table1.remove();
     Element table2 = doc2.getElementsByTag("table").first();
     table2.remove();
     Element title = doc2.getElementsByTag("title").first();
     title.html("电费查询");
   
     Elements payLoginDiv = doc2.select("div#payLoginDiv");
     payLoginDiv.attr("style","display:none");
     outhtml = doc2.html();
     System.out.println("--3*****-"+title.html());
 // System.out.println(outhtml);
 
  return outhtml;
 }
 
 /*
 
 public String commitPage(String feeCode, String yanzhengma, String cookie, ServletContext sc, HttpSession session)
 throws Exception
 {
  System.out.println("feeCode:" + feeCode);
  System.out.println("yanzhengma:" + yanzhengma);
  System.out.println("cookie:" + cookie);
 
  HttpClient httpClient1 = new HttpClient();
  httpClient1.getHostConfiguration()
  .setHost("www.sd.10086.cn", 80, "http");
  PostMethod post = new PostMethod("/lefu/web2/getDianFeiQianFei.do");
  NameValuePair simcard = new NameValuePair("payFeeType","08");
  NameValuePair simcard1 = new NameValuePair("types","08WDS02WDS03WNS04WNS");
  NameValuePair simcard2 = new NameValuePair("cityCode","01");
  NameValuePair simcard3 = new NameValuePair("feeCode",feeCode);
  NameValuePair simcard4 = new NameValuePair("yanzhengma",yanzhengma);
  post.setRequestBody(new NameValuePair[] { simcard, simcard1, simcard2, simcard3, simcard4});
  post.setRequestHeader("Cookie", cookie);
  httpClient1.executeMethod(post);
  System.out.println("555 = "+post.getResponseBodyAsString());
  post.releaseConnection();
 
  return post.getResponseBodyAsString().trim();
 }
 public static String savegif(GetMethod getMethod, String filename) throws IOException
 {
  File storeFile = new File(filename); 
  FileOutputStream output = new FileOutputStream(storeFile); 
  output.write(getMethod.getResponseBody()); 
  output.close();
  return filename;
 }
// public String commitPage(String feeCode, String yanzhengma, String cookie, ServletContext sc, HttpSession session)
// throws CustomException,Exception
// {
if (sc == null)
{
throw new CustomException("ServletContext 为空,返回");
}
if(session==null)
{
throw new CustomException("HttpSession 为空,返回");
}
// HttpClient client = new HttpClient();
// client.getHostConfiguration().setHost("http://www.sd.10086.cn", 80, "http");
// PostMethod post = new PostMethod("lefu/web2/getDianFeiQianFei.do");
// NameValuePair simcard = new NameValuePair("payFeeType","08");
// NameValuePair simcard1 = new NameValuePair("types","08WDS02WDS03WNS04WNS");
// NameValuePair simcard2 = new NameValuePair("cityCode","01");
// NameValuePair simcard3 = new NameValuePair("feeCode",feeCode);
// NameValuePair simcard4 = new NameValuePair("yanzhengma",yanzhengma);
// post.setRequestBody(new NameValuePair[] { simcard, simcard1, simcard2, simcard3, simcard4});
// post.setRequestHeader("Cookie", cookie);
// client.executeMethod(post);
// //打印服务器返回的状态
// System.out.println("111="+post.getStatusLine());
// //打印结果页面
// String response = new String(post.getResponseBodyAsString());
// //打印返回的信息
// System.out.println("222="+response);
// post.releaseConnection();
// return "";
// }
*/
}
 

 


?

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值