Java 模拟HTTP登录代码

youcaihua 贡献于2014-02-28

作者 微软用户  创建于2010-05-18 09:28:00   修改者微软用户  修改于2010-05-18 09:32:00字数8389

文档摘要:Java 模拟HTTP登录代码
关键词:

JAVA,模拟HTTP登录 Java代码 package com.potevio.mobilenet; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; public class TestPost { public static void testPost() throws IOException { //连接地址 String surl = "http://219.238.180.***:80/.../loginservlet?command=login"; /** * 首先要和URL下的URLConnection对话。 URLConnection可以很容易的从URL得到。比如: // Using * java.net.URL and //java.net.URLConnection */ URL url = new URL(surl); URLConnection connection = url.openConnection(); /** * 然后把连接设为输出模式。URLConnection通常作为输入来使用,比如下载一个Web页。 * 通过把URLConnection设为输出,你可以把数据向你个Web页传送。下面是如何做: */ connection.setDoOutput(true); /** * 最后,为了得到OutputStream,简单起见,把它约束在Writer并且放入POST信息中,例如: ... */ OutputStreamWriter out = new OutputStreamWriter(connection .getOutputStream(), "UTF-8"); out.write("user_account=admin&user_password=******"); //post的关键所在! // remember to clean up out.flush(); out.close(); /** * 这样就可以发送一个看起来象这样的POST: * POST /jobsearch/jobsearch.cgi HTTP 1.0 ACCEPT: * text/plain Content-type: application/x-www-form-urlencoded * Content-length: 99 username=bob password=someword */ // 一旦发送成功,用以下方法就可以得到服务器的回应: String sCurrentLine; String sTotalString; sCurrentLine = ""; sTotalString = ""; InputStream l_urlStream; l_urlStream = connection.getInputStream(); // 传说中的三层包装阿! BufferedReader l_reader = new BufferedReader(new InputStreamReader( l_urlStream)); while ((sCurrentLine = l_reader.readLine()) != null) { sTotalString += sCurrentLine + "\r\n"; } System.out.println(sTotalString); } public static void main(String[] args) throws IOException { testPost(); } } 百度提交 public static void loginBaidu() { URL url = null; HttpURLConnection httpurlconnection = null; try { url = new URL("http://www.baidu.com/"); httpurlconnection = (HttpURLConnection) url.openConnection(); httpurlconnection.setRequestProperty("User-Agent", "Internet Explorer"); httpurlconnection.setRequestProperty("Host", "www.baidu.com"); httpurlconnection.connect(); String cookie0 = httpurlconnection.getHeaderField("Set-Cookie"); System.out.println(cookie0);//打印出cookie httpurlconnection.disconnect(); // String cookie0 = // "BAIDUID=8AF5EA24DBF1275CE15C02B5FF65A265:FG=1;BDSTAT=61a1d3a7118ce8a7ce1b9d16fdfaaf51f3deb48f8e5494eef01f3a292cf5b899; // BDUSE=deleted"; url = new URL("http://passport.baidu.com/?login"); String strPost = "username=xxxxxx&password=yyyyyyy&mem_pass=on"; httpurlconnection = (HttpURLConnection) url.openConnection(); httpurlconnection.setFollowRedirects(true); httpurlconnection.setInstanceFollowRedirects(true); httpurlconnection.setDoOutput(true); // 需要向服务器写数据 httpurlconnection.setDoInput(true); // httpurlconnection.setUseCaches(false); // 获得服务器最新的信息 httpurlconnection.setAllowUserInteraction(false); httpurlconnection.setRequestMethod("POST"); httpurlconnection .addRequestProperty( "Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-silverlight, */*"); httpurlconnection .setRequestProperty("Referer", "http://passport.baidu.com/?login&tpl=mn&u=http%3A//www.baidu.com/"); httpurlconnection.setRequestProperty("Accept-Language", "zh-cn"); httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpurlconnection.setRequestProperty("Accept-Encoding", "gzip, deflate"); httpurlconnection .setRequestProperty( "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Foxy/1; .NET CLR 2.0.50727;MEGAUPLOAD 1.0)"); httpurlconnection.setRequestProperty("Host", "passport.baidu.com"); httpurlconnection.setRequestProperty("Content-Length", strPost .length() + ""); httpurlconnection.setRequestProperty("Connection", "Keep-Alive"); httpurlconnection.setRequestProperty("Cache-Control", "no-cache"); httpurlconnection.setRequestProperty("Cookie", cookie0); httpurlconnection.getOutputStream().write(strPost.getBytes()); httpurlconnection.getOutputStream().flush(); httpurlconnection.getOutputStream().close(); httpurlconnection.connect(); int code = httpurlconnection.getResponseCode(); System.out.println("code " + code); String cookie1 = httpurlconnection.getHeaderField("Set-Cookie"); System.out.print(cookie0 + "; " + cookie1); httpurlconnection.disconnect(); url = new URL("http://www.baidu.com/"); httpurlconnection = (HttpURLConnection) url.openConnection(); httpurlconnection.setRequestProperty("User-Agent", "Internet Explorer"); httpurlconnection.setRequestProperty("Host", "www.baidu.com"); httpurlconnection.setRequestProperty("Cookie", cookie0 + "; " + cookie1); httpurlconnection.connect(); InputStream urlStream = httpurlconnection.getInputStream(); BufferedInputStream buff = new BufferedInputStream(urlStream); Reader r = new InputStreamReader(buff, "gbk"); BufferedReader br = new BufferedReader(r); StringBuffer strHtml = new StringBuffer(""); String strLine = null; while ((strLine = br.readLine()) != null) { strHtml.append(strLine + "\r\n"); } System.out.print(strHtml.toString()); } catch (Exception e) { e.printStackTrace(); } finally { if (httpurlconnection != null) httpurlconnection.disconnect(); } } 模拟登录 这个要分两步,先用GET方法取得页面源码,分析出mpc的值,然后用POST方法发送数据就能登录了。当然一切工作之前要设置好CookieHandler post页面: http://www.songtaste.com/info_oper.php?tag=signin&pageref= post参数就4个而已, name=yourName&pwd=yourPassword&B12=Login&mpc=分析得到的mpc 看如下例子: http://zhidao.baidu.com/question/141336096.html 将这个例子中的如下语句改一下就能收到数据的 connection.getInputStream().close(); // import java.io.BufferedInputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookiePolicy; import java.net.HttpURLConnection; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SongTaste { private static String baseURL="http://www.songtaste.com"; private static String loginURL=baseURL+"/signin.php"; private static String actionURL=baseURL+"/info_oper.php?tag=signin&pageref="; private static String musicURL=baseURL+"/music/"; private static CookieManager cm; static{ cm=new CookieManager(); cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL); CookieHandler.setDefault(cm); } public static void main(String[] args) throws Exception{ // HttpURLConnection.setFollowRedirects(true); login("abcmusic","000000"); listContents(); } private static void listContents() throws Exception { byte[] dat=new HttpGet(musicURL).data; String src=new String(dat,"gbk"); Matcher m=Pattern.compile("MSL\\(.*?\\)").matcher(src); while(m.find()) System.out.println(m.group()); } private static void login(String name,String pwd){ byte[] dat=new HttpGet(loginURL).data; String src=new String(dat); Matcher m=Pattern.compile("name=mpc.*?>").matcher(src); String mpc=""; if(m.find()){ mpc=m.group(); // System.out.println(mpc); mpc=mpc.substring(15,mpc.length()-1); // System.out.println(mpc); } //do login new HttpPost(actionURL,String.format("name=%s&pwd=%s&B12=Login&mpc=%s",name,pwd,mpc)); } private static class HttpGet extends Thread{ private static final int bufferSize=1024; private String ustr; private byte[] data; private HttpGet(String u,String...ref){ ustr=u; start(); try {join();} catch (Exception e) {} } public void run(){ try{ URL u = new URL(ustr); HttpURLConnection uc=(HttpURLConnection)u.openConnection(); byte[] b={}; byte[] t=new byte[bufferSize]; int r; BufferedInputStream bin=new BufferedInputStream(uc.getInputStream()); while((r=bin.read(t))>-1){ b=putData(b,t,r); } bin.close(); uc.disconnect(); data=b; }catch(Exception e){} } private final byte[] putData(byte[] b, byte[] t, int r) { byte[] tb=new byte[b.length+r]; System.arraycopy(b, 0, tb, 0, b.length); System.arraycopy(t, 0, tb, b.length, r); return tb; } } private static class HttpPost extends Thread{ private static int blen=1024; private static String contentType="application/x-www-form-urlencoded"; private String url,pms; private byte[] dat={}; private HttpPost(String u,String p){ url=u; pms=p; start(); try{join();}catch(Exception e){} } public void run(){ try{ URL u = new URL(url); HttpURLConnection connection=(HttpURLConnection)u.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type",contentType); connection.setRequestProperty("Content-Length",String.valueOf(pms.length())); connection.setUseCaches(false); connection.setDoOutput(true); connection.setDoInput(true); DataOutputStream dout=new DataOutputStream(connection.getOutputStream()); dout.write(pms.getBytes()); dout.flush(); dout.close(); InputStream in=connection.getInputStream(); BufferedInputStream bin=new BufferedInputStream(in); byte[] buff=new byte[blen],bs={}; int r; while((r=bin.read(buff))>-1){ bs=putData(bs,buff,r); } bin.close(); connection.disconnect(); dat=bs; }catch(Exception e){} } private final byte[] putData(byte[] b, byte[] t, int r) { byte[] tb=new byte[b.length+r]; System.arraycopy(b, 0, tb, 0, b.length); System.arraycopy(t, 0, tb, b.length, r); return tb; } } }

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 2 金币 [ 分享文档获得金币 ] 0 人已下载

下载文档