萧逸闲侃

技术爱好者

java用HttpURLConnection模拟post提交数据

java.net.HttpURLConnection可以模拟http的post、get提交数据

这个测试类:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class testPost
{
     public static void main(String[] args) throws UnsupportedEncodingException
     {
    long bc = System.currentTimeMillis();
    for(int i=0;i<100;i++)
    {
       long b = System.currentTimeMillis();
       String str = "<xml><test>aa 1_ 1 </test><name>姓名</name></xml>"+i*100;
       str = URLEncoder.encode(str,"utf-8");
       testPost.sendRequest(str);
       long c = System.currentTimeMillis();
       System.out.println("第"+i+"此" + "耗时:" + (c-b));
    }
    long cc = System.currentTimeMillis();
    System.out.println("耗时:" + (bc-cc));

   
   
     }
    
     public static String sendRequest(String strXml)
     {
         StringBuffer buffer = null;
    HttpURLConnection c = null;
         try
         {
        System.out.println("go!");
             URL url=new URL("http://localhost:8080/xfirews/servlet/getPhpServlet");
             c=(HttpURLConnection)url.openConnection();
             c.setRequestMethod("POST");
             c.setRequestProperty("content-type", "text/html");
             c.setRequestProperty("Accept-Charset", "utf-8");
             c.setDoOutput(true);
             c.setDoInput(true);
             //c.setConnectTimeout(30000);//设置连接主机超时(单位:毫秒)
             //c.setReadTimeout(30000);//设置从主机读取数据超时(单位:毫秒)
             c.connect();
             System.out.println("-------begin--------");
             PrintWriter out = new PrintWriter(c.getOutputStream());//发送数据
             out.print(strXml);
             out.flush();
             out.close();
            
             //c.geth
             String header;
             for(int i=0;true;i++){
                 header=c.getHeaderField(i);
                 if(header==null)break;
                 System.out.println("header:"+header);
                 //System.out.println(c.getContentType());
             }
             int res =0;
             res = c.getResponseCode();
             System.out.println("res="+res);

             if (res == 200)
             {
             
              InputStream u=c.getInputStream();//获取servlet返回值,接收
              BufferedReader in = new BufferedReader(new InputStreamReader(u));
              buffer = new StringBuffer();
              String line = "";
              while ((line = in.readLine()) != null){
                buffer.append(line);
              }
              System.out.println(">>"+buffer.toString());
             }else
             {
            System.out.println("------接收出错了-------");
             }
             c.disconnect();
             System.out.println("-------end--------");
           
             //System.out.println();
         }catch (Exception e) {
             // TODO: handle exception
        System.out.println("异常!");
             System.out.println(e.toString());
         }
         return buffer.toString();
     }
}

这是接收数据并返回结果的servlet

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Writer;

import java.net.URLConnection;
import java.net.URLEncoder;

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


/**
*
*/
/**
* @author Administrator
*
*/
public class getPhpServlet extends HttpServlet
{
    /**
     * Constructor of the object.
     */
    public getPhpServlet()
    {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy()
    {
        super.destroy(); // Just puts "destroy" string in log

        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
               throws ServletException, IOException
    {
        doPost(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to
     * post.
     *
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException
    {
        response.setContentType("text/html;charset=utf-8");
        //response.setStatus(HttpServletResponse.SC_OK);
        try
        {
            String a = getDoc(request);
            System.out.println("接收数据" + a);
        }catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String back = "返回数据";
        Writer w = response.getWriter();
        w.write(back);
        w.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException
     *             if an error occure
     */
    public void init() throws ServletException
    {
        // Put your code here
    }

    //发送数据
    public void send(URLConnection connection, String strXml)
    {
        // 产生输出流
        BufferedOutputStream out = null;
        BufferedInputStream bin = null;

        try
        {
            out = new BufferedOutputStream(connection.getOutputStream());

            String mob = null;
            mob = URLEncoder.encode(strXml, "UTF-8");
            out.write(mob.getBytes());
            out.flush();

            // 接受服务器response
            bin = new BufferedInputStream(connection.getInputStream());

            int len = bin.available();
            System.out.println("len:" + len);

            byte [] tmp = new byte[len];
            bin.read(tmp);
            System.out.println("return value:" + new String(tmp));
        }catch (Throwable t)
        {
            t.printStackTrace();
        }
    }
    // 获取post数据
    public String getDoc(HttpServletRequest request) throws Exception
    {
        char [] readerBuffer = new char[request.getContentLength()];
        BufferedReader bufferedReader = request.getReader();
        int portion = bufferedReader.read(readerBuffer);
        int amount = portion;

        while (amount < readerBuffer.length)
        {
            portion = bufferedReader.read(readerBuffer, amount,
                                          readerBuffer.length - amount);
            amount = amount + portion;
        }

        StringBuffer stringBuffer = new StringBuffer((int) (readerBuffer.length * 1.5));

        for (int index = 0; index < readerBuffer.length; index++)
        {
            char c = readerBuffer[index];
            stringBuffer.append(c);
        }

        String xml = urlDecode(stringBuffer.toString());

        return xml;
    }

    /*
     * InputStream is=request.getInputStream(); DocumentBuilderFactory
     * factory=DocumentBuilderFactory.newInstance(); DocumentBuilder
     * builder=factory.newDocumentBuilder(); Document doc=builder.parse(is);
     *
     * //获得xml字符串后,使用dom4j parse为DOM对象,就可以了�?? Document document =
     * DocumentHelper.parseText(xml);
     */
    public String urlDecode(String value)
    {
        try
        {
            return java.net.URLDecoder.decode(value, "utf-8");
        }catch (Exception ex)
        {
            ex.printStackTrace();
        }

        return value;
    }
}


阅读更多
个人分类: javaWeb http
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭