JAVA网络编程之模拟表单提交

这一篇博客是对上一篇《JAVA网络编程之获取网络资源》的扩充,这一篇将使用HttpURLConnection来模拟一个表单的提交。在B/S架构的系统中,请求时通过浏览器与服务端进行交互的,提交请求参数时使用form表单进行提交,但是有很多时候,我们需要在程序中直接调用HTTP接口,同时需要传递一些参数,那么这个时候我们就可以通过使用HttpURLConnection来模拟表单的提交过程。

首先,我们可以对请求进行封装

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 请求
 * 
 * @author jianggujin
 * 
 */
public class HttpRequest
{
   /** 请求地址 **/
   private String url = null;
   /** 请求方法 **/
   private RequestMethod method = RequestMethod.GET;
   /** 编码 **/
   private String charset = "UTF-8";
   /** 请求头信息 **/
   private Map<String, String> headers = new HashMap<String, String>();
   /** 请求参数 **/
   private Map<String, List<String>> params = new HashMap<String, List<String>>();

   /**
    * 默认构造方法
    */
   public HttpRequest()
   {
   }

   /**
    * 构造方法
    * 
    * @param url
    */
   public HttpRequest(String url)
   {
      this.url = url;
   }

   /**
    * 构造方法
    * 
    * @param url
    * @param method
    */
   public HttpRequest(String url, RequestMethod method)
   {
      this.url = url;
      this.method = method;
   }

   /**
    * 获得请求地址
    * 
    * @return
    */
   public String getUrl()
   {
      return url;
   }

   /**
    * 设置请求地址
    * 
    * @param url
    */
   public void setUrl(String url)
   {
      this.url = url;
   }

   /**
    * 获得请求方法
    * 
    * @return
    */
   public RequestMethod getMethod()
   {
      return method;
   }

   /**
    * 设置请求方法
    * 
    * @param method
    */
   public void setMethod(RequestMethod method)
   {
      this.method = method;
   }

   /**
    * 获得编码
    * 
    * @return
    */
   public String getCharset()
   {
      return charset;
   }

   /**
    * 设置编码
    * 
    * @param charset
    */
   public void setCharset(String charset)
   {
      this.charset = charset;
   }

   /**
    * 添加头信息
    * 
    * @param name
    * @param value
    */
   public void addHeader(String name, String value)
   {
      headers.put(name, value);
   }

   /**
    * 添加请求参数
    * 
    * @param name
    * @param value
    */
   public void addParam(String name, String value)
   {
      List<String> list = params.get(name);
      if (list == null)
      {
         list = new ArrayList<String>();
         params.put(name, list);
      }
      list.add(value);
   }

   /**
    * 设置请求参数
    * 
    * @param name
    * @param value
    */
   public void setParam(String name, String value)
   {
      List<String> list = params.get(name);
      if (list == null)
      {
         list = new ArrayList<String>();
         params.put(name, list);
      }
      else
      {
         // 清空已有参数
         list.clear();
      }
      list.add(value);
   }

   /**
    * 获得请求头迭代器
    * 
    * @return
    */
   public Iterator<Entry<String, String>> getHeaders()
   {
      return headers.entrySet().iterator();
   }

   /**
    * 获得请求参数迭代器
    * 
    * @return
    */
   public Iterator<Entry<String, List<String>>> getParams()
   {
      return params.entrySet().iterator();
   }

}

/**
 * 请求方法
 * 
 * @author jianggujin
 * 
 */
enum RequestMethod
{
   GET, POST
}

在HttpRequest类中,包含了一个请求的基本信息,然后我们再封装一个类用于HTTP的请求。

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

/**
 * Http请求客户端
 * 
 * @author jianggujin
 * 
 */
public abstract class HttpClient
{
   /** 连接超时时间 **/
   private int connectTimeOut = 10 * 1000;
   /** 读超时时间 **/
   private int readTimeOut = 10 * 1000;

   /**
    * 获得连接超时时间
    * 
    * @return
    */
   public int getConnectTimeOut()
   {
      return connectTimeOut;
   }

   /**
    * 设置连接超时发时间
    * 
    * @param connectTimeOut
    */
   public void setConnectTimeOut(int connectTimeOut)
   {
      this.connectTimeOut = connectTimeOut;
   }

   /**
    * 获得读超时时间
    * 
    * @return
    */
   public int getReadTimeOut()
   {
      return readTimeOut;
   }

   /**
    * 设置读超时时间
    * 
    * @param readTimeOut
    */
   public void setReadTimeOut(int readTimeOut)
   {
      this.readTimeOut = readTimeOut;
   }

   /**
    * 执行
    */
   public void execute(HttpRequest request) throws IOException
   {
      String url = request.getUrl();
      // GET方式请求
      if (request.getMethod() == RequestMethod.GET)
      {
         // 拼接参数
         if (url.indexOf('?') != -1)
         {
            if (url.endsWith("?"))
            {
               url += dealParam(request);
            }
            else
            {
               if (url.endsWith("&"))
               {
                  url += dealParam(request);
               }
               else
               {
                  url += ("&" + dealParam(request));
               }
            }
         }
         else
         {
            url += ("?" + dealParam(request));
         }
      }
      // 获得Http连接
      HttpURLConnection connection = (HttpURLConnection) new URL(url)
            .openConnection();
      // 设置超时时间
      connection.setConnectTimeout(connectTimeOut);
      connection.setReadTimeout(readTimeOut);

      // 设置请求头
      Iterator<Entry<String, String>> headers = request.getHeaders();
      while (headers.hasNext())
      {
         Entry<String, String> entry = headers.next();
         connection.setRequestProperty(entry.getKey(), entry.getValue());
      }

      connection.setUseCaches(false);

      // 如果是POST请求
      if (request.getMethod() == RequestMethod.POST)
      {
         connection.setDoInput(true);
         connection.setDoOutput(true);
         connection.setRequestMethod("POST");
      }

      connection.connect();

      // 如果是POST请求
      if (request.getMethod() == RequestMethod.POST)
      {
         OutputStreamWriter writer = new OutputStreamWriter(
               connection.getOutputStream(), request.getCharset());
         writer.write(dealParam(request));
         writer.flush();
         writer.close();
      }

      if (connection.getResponseCode() == HttpURLConnection.HTTP_OK)
      {
         onSuccess(HttpURLConnection.HTTP_OK, connection.getInputStream());
      }
      else
      {
         onSuccess(connection.getResponseCode(), connection.getErrorStream());
      }
      connection.disconnect();
   }

   /**
    * 处理请求参数
    * 
    * @param request
    * @return
    * @throws IOException
    */
   private String dealParam(HttpRequest request) throws IOException
   {
      StringBuilder builder = new StringBuilder();
      Iterator<Entry<String, List<String>>> iterator = request.getParams();
      int count = 0;
      // 遍历请求参数
      while (iterator.hasNext())
      {
         Entry<String, List<String>> entry = iterator.next();
         List<String> list = entry.getValue();
         for (String string : list)
         {
            if (count > 0)
            {
               builder.append("&");
            }
            builder.append(entry.getKey()).append("=");
            if (request.getMethod() == RequestMethod.GET)
            {
               builder.append(URLEncoder.encode(string, request.getCharset()));
            }
            else
            {
               builder.append(string);
            }
            count++;
         }
      }
      return builder.toString();
   }

   /**
    * 出错时执行
    * 
    * @param code
    * @param stream
    * @throws IOException
    */
   public abstract void onError(int code, InputStream stream)
         throws IOException;

   /**
    * 成功时执行
    * 
    * @param code
    * @param stream
    * @throws IOException
    */
   public abstract void onSuccess(int code, InputStream stream)
         throws IOException;
}

为了方便测试,简单的编写一个Servlet,代码如下:

package com.jhq.wx.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Test extends HttpServlet
{
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
   {
      System.out.println(request.getParameter("p1"));
      System.out.println(request.getParameter("p2"));
   }

   protected void doPost(HttpServletRequest request,
         HttpServletResponse response) throws ServletException, IOException
   {
      request.setCharacterEncoding("UTF-8");
      System.out.println(request.getParameter("p1"));
      System.out.println(request.getParameter("p2"));
   }
}

最后编写一个测试类,测试模拟表单提交

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Test
{
   public static void main(String[] args)
   {
      HttpRequest request = new HttpRequest("http://127.0.0.1/wx/s");
      request.addParam("p1", "123");
      request.addParam("p2", "蒋固金");
      request.setMethod(RequestMethod.POST);
      HttpClient client = new HttpClient()
      {

         @Override
         public void onSuccess(int code, InputStream stream) throws IOException
         {
            // 内容是文本,直接以缓冲字符流读取
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                  stream, "UTF-8"));
            String data = null;
            while ((data = reader.readLine()) != null)
            {
               System.out.print(data);
            }
            reader.close();
         }

         @Override
         public void onError(int code, InputStream stream)
         {
            System.out.println("请求出现异常");
         }
      };
      try
      {
         client.execute(request);
      }
      catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}

运行之后,我们可以看到服务端后台输出:
123
蒋固金

这样就完成了Java模拟表单提交的操作。

上一篇:win引导修复


下一篇:如何安放你的大文件,MongoDB GridFS可以帮助你