您的位置:首页 > 其它

模拟浏览器向服务器发送和接收数据

2011-02-17 17:01 253 查看
创建一个服务器程序,用来接收和返回数据:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println(request.getMethod());    //获取请求方式
System.out.println(request.getHeader("referer")); //获取请求页面
System.out.println(request.getParameter("name")); //获取参数
response.getOutputStream().write("Hello".getBytes());   //向浏览器回送数据
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
接下来,再创建一个Java程序向这个服务器程序发送请求,类 HttpURLConnection提供方法获取和发送请求数据.但是构造方法
protected
HttpURLConnection(URL u)

表明我们不能直接创建这个对象,也没有任何静态方法能够返回这个对象.于是我们需要绕一把..先获得 URL对象,再利用
openConnection()返回
HttpURLConnection对象:
public void sendHttp() throws IOException{
URL url = new URL("http://localhost:8080/ImitateRequest/servlet/servlet");    //设置要访问的链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();//获取HttpURLConnection的对象
    conn.setDoOutput(true);    //默认值为false,不能传递参数  
    conn.setRequestMethod("POST");//设置请求方式  
conn.setRequestProperty("referer", "http://www.sina.com/index.html");
OutputStream out = conn.getOutputStream();
    out.write("name=aaaa".getBytes());     //向服务器发送一个值为"aaaa"的name参数,如果conn的DoOutput属性值为false,此处将抛出异常  
    conn.getResponseCode();    //获取响应状态码  
}
以上是发送一次请求需要掌握的方法,接下来是读取一次请求:
public void readHttp() throws IOException{
  URL url = new URL("http://localhost:8080/ImitateRequest/servlet/servlet");    //设置请求的链接
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  
  System.out.println(conn.getResponseCode());    //查看响应状态码
  System.out.println(conn.getHeaderField("Content-Length")); //响应文本内容的长度
  InputStream in = conn.getInputStream();  //获取一个和服务器返回的内容相关联的流
  try{
int len = 0;
byte[] buffer = new byte[1024];
while((len = in.read(buffer))>0){
    System.out.println(new String(buffer,0,len));    //输出到控制台
}
  }finally{
if(in!=null)
    try{
  in.close();
    }catch(Exception e){
    }
  }
}
常用的一些HTTP协议请求头:
RequestGET /h.gif?pid=113&monkey=cool HTTP/1.1请求方式 请求路径 请求版本
Acceptimage/png, image/svg+xml, image/*;q=0.8, */*;q=0.5浏览器可接收的类型
Refererhttp://hao123.com/来源路径
Accept-Languagezh-CN浏览器可以接收的语言
User-AgentMozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)浏览器的厂商信息
Content-Type text/html; charset=UTF-8数据的内容类型
Accept-Encodinggzip, deflate浏览器可以接收压缩后的数据
Host nsclick.baidu.com请求的主机IP和端口号
Content-Length289用于指定数据的总长度
Connection Keep-Alive维持一个活动连接
Cache-Controlno-cache缓存情况
Cookie BAIDUID=304614CF0781D6FABA00280E60983AF5:FG=1COOKIE
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐