URL编程:java程序模拟post提交表单_小圣_新浪博客

假设一个地址为:”http://locolhost:8080/test/”,表单提交后的action为”login.action”。

String urlString = “http://locolhost:8080/test/login.action”;

1,首先创建URLConnection对象

  URL url = new

URL(urlString);

  URLConnection conn =

url.openConnection();

2,建立用于输出的连接

  conn.setDoOutput(true);

3,获取输出流

  PrintWriter out = new

PrintWriter(conn.getOutputStream());

4,输出post的参数,nameValuePairs为用户名与密码的参数对

  boolean first = true;

  for(Map.Entry pair :

nameValuePairs.entrySet())

  {

   if(first)

first = false;

   else

out.print(‘&’);

   String name

= pair.getKey();

   String value

= pair.getValue();

  

out.print(name);

  

out.print(‘=’);

  

out.print(URLEncoder.encode(value,”UTF-8″));

  }

  out.close();

5,获取输入流

  Scanner in;

  StringBuilder response = new

StringBuilder();

  try

  {

   in = new

Scanner(conn.getInputStream());

  }

  catch(IOException e)

  {

   if(!(conn

instanceof HttpURLConnection)) throw

e;   

//此处为了获取错误页面,如404等

   InputStream

err = ((HttpURLConnection)conn).getErrorStream();

   if(err ==

null) throw e;

   in = new

Scanner(err);

  }

6,得到输出结果

  while(in.hasNextLine())

  {

  

response.append(in.nextLine());

  

response.append(“\n”);

  }

  in.close();

  return

response.toString();

来源URL:http://blog.sina.com.cn/s/blog_6cadcce70101hl43.html