本文转自:http://dddspace.com/2009/06/java-net-operation-session-get-post-method.html
import java.io.BufferedReader; |
02 | import java.io.IOException; |
03 | import java.io.InputStreamReader; |
04 | import java.net.MalformedURLException; |
05 | import java.net.ProtocolException; |
07 | import java.net.HttpURLConnection; |
09 | public class FarmerHelper { |
13 | * @throws ProtocolException |
15 | public static void main(String[] args) throws ProtocolException { |
21 | HttpURLConnection loginConn = null ; |
22 | HttpURLConnection homeConn = null ; |
24 | loginUrl = new URL(loginUrlStr); |
25 | homeUrl = new URL(homeUrlStr); |
27 | loginConn = (HttpURLConnection) loginUrl.openConnection(); |
28 | homeConn = (HttpURLConnection) homeUrl.openConnection(); |
29 | } catch (IOException e) { |
30 | print( "Conn't open the url connection!" ); |
33 | } catch (MalformedURLException e) { |
34 | print( "Illegal URL!" ); |
38 | loginConn.setRequestMethod( "POST" ); |
39 | loginConn.setRequestProperty( "User-Agent" , |
40 | "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.10)" |
41 | + " Gecko/2009042316 Firefox/3.0.10" ); |
42 | loginConn.setRequestProperty( "Keep-Alive" , "300" ); |
43 | loginConn.setRequestProperty( "Connection" , "keep-alive" ); |
44 | loginConn.setRequestProperty( "email" , "alswlwangzi@163.com" ); |
45 | loginConn.setRequestProperty( "password" , "xh77Gffb_i" ); |
46 | loginConn.setRequestProperty( "submit" , "登录" ); |
47 | loginConn.setRequestProperty( "Keep-Alive" , "300" ); |
51 | String headerName = null ; |
59 | cookie = loginConn.getHeaderField( "Set-Cookie" ); |
62 | homeConn.setRequestProperty( "Cookie" , cookie); |
63 | homeConn.setRequestMethod( "GET" ); |
66 | BufferedReader in = new BufferedReader( new InputStreamReader( |
67 | homeConn.getInputStream())); |
68 | String lineStr = null ; |
70 | while ((lineStr = in.readLine()) != null ) { |
72 | print( new String(lineStr.getBytes( "GBK" ), "UTF-8" )); |
74 | } catch (IOException e) { |
75 | print( "conn't connect to the server!" ); |
80 | private static void print(Object o) { |
81 | System.out.println(o); |
83 | } 想法总是好的,现实总是残酷的,调试很久,用WireShark抓包,都是有Length Required错误,这个比较头疼,我感觉是我session传递的问题(其实不是,后来发现是Post的格式问题),于是网上找来一个Session操作类。 猛击这里下载cookiemanager 同时你可以参考这个类作者的文章猛击这里打开HOW-TO: Handling cookies using the java.net.* API,谢谢这位外国朋友的帮助。 可惜尽管有这个外国朋友帮助,我写了第二个版本,仍然遇到了相同问题,Length Required… 崩溃了,开始查找网络编程书,同时参考WireShark的抓包,我惊讶的发现,我把数据域写到了Headers里面去了。 这个致命性的错误导致服务器不能找到正确的数据,并且没有提供数据域的大小Content-Length,所以导致服务器报错。 最后再借花献佛,送上一个完整操作Http GET/POST的类猛击这里下载httprequestproxy依然感谢原作者,猛击这里打开原文链接友情提示一下,这个类是07年写的,里面有一些注释说明在1.4和1.5下几个参数不一样,我没有亲测,建议使用1.5的设置 嗯,有这两个类,明天工作应该会轻松一些,继续fighting!
|