楼主httpURLConncetion发送post请求和使用session都是tomcat等web容器封装好的,我也研究过httpUrlconncetion但和session无关
下面是一个使用HttpURLConncetion读取百度源代码的程序,保存成PageReader.java即可使用,你也可以读取其他网站的源代码
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class PageReader{
private HttpURLConnection conn=null;
public int connect(String url) throws Exception
{
URL url1=new URL(url);
conn=(HttpURLConnection) url1.openConnection();
conn.setReadTimeout(600);
System.out.println("Response is"+conn.getResponseCode());
System.out.println(conn.getURL().toString());
return conn.getResponseCode();
}
public String readContent()throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb=new StringBuffer();
String content="";
while((content=br.readLine())!=null)
{
sb.append(content);
}
return sb.toString();
}
public void disConnect()
{
if(conn!=null)
{
conn.disconnect();
}
}
public static void main(String args[])
{
PageReader pr=new PageReader();
String content;
try {
pr.connect("http://www.baidu.com");
content = pr.readContent();
System.out.println(content);
pr.disConnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}