java模拟浏览器post数据
代码如下
HttpURLConnection conn = null;
conn = (HttpURLConnection) goal.openConnection();
HttpURLConnection.setFollowRedirects(true);
conn.setFollowRedirects(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
String cookie = conn.getHeaderField( "Set-Cookie ");
conn.setRequestProperty( "Cookie ", cookie);
conn.setRequestMethod( "POST ");
conn.setRequestProperty( "User-Agent ",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000 ");
conn.setRequestProperty( "Content-Type ",
"application/x-www-form-urlencoded ");
conn.setRequestProperty( "Content-Language ", "en-US ");
conn.setRequestProperty( "Content-Length ", " " + data.length());
Debug时到conn.setRequestProperty( "Cookie ", cookie)总是提示出错:already connection 那位高手能解决一下啊,谢谢
------解决方案--------------------补充一下:我使用的是jdk1.5
------解决方案--------------------String cookie = conn.getHeaderField( "Set-Cookie ");
怀疑这句getHeader会导致POST请求发出,
之后你再setRequestHeader连接就已经open了。
把GetHeaderfield在connection. output之后, POST出去, 获取到返回页面信息再GetHeaderField
猜测的。 没验证
------解决方案-------------------- String cookie = conn.getHeaderField( "Set-Cookie ");
conn.setRequestProperty( "Cookie ", cookie);
这两个不能同时用
getHeaderField是连接之后用的,setRequestProperty是连接之前用的