用HttpURLConnection在服务器端发起HTTP Post请求的例子

通常情况下,http请求都是从浏览器端发起的,如提交一个表单,或点击一个链接,都会对服务器发送一个http请求。

但如果我们想在服务器发出一个http请求,如何才能做到呢,如果只是简单的http访问,java.net.URL就足够了,如:

    URL url = new URL("http://www.baidu.com");

    InputStream ins = url.openStream();

    //通过这个InputStream对象就可拿到返回的HTML代码

 

 

但如果我们要从服务器对远程URL发出http post访问,并且要传递一些参数,甚至还要设置某些Cookie值,那就要

借助HttpURLConnection这个类了,我们可以用URL.openConnection()方法来得到这个类的对象,具体请看下例:

 

protected void doPost(HttpServletRequest request,

            HttpServletResponse response) throws Exception {

       

        HttpURLConnection httpConn = null;

        try {

            StringBuffer paramData = getQueryString(request);  

            String urlString = "http://localhost:8080/myweb/login.do";

   

            URL url = new URL(urlString);

            httpConn = (HttpURLConnection) url.openConnection();

            httpConn.setDoInput(true);

            httpConn.setDoOutput(true);

            httpConn.setRequestMethod("POST");

            httpConn.setRequestProperty("Content-Type",

                    "application/x-www-form-urlencoded");

            String cookieString = getCookieString(request);

            if (cookieString.length() > 0) // 往远程URL传递Cookie

                httpConn.setRequestProperty("Cookie", cookieString);

   

            OutputStream os = httpConn.getOutputStream();

            os.write(paramData.toString().getBytes()); // 往远程URL传递参数

            os.flush();

            os.close();

   

            int code = httpConn.getResponseCode();

            if (code == 200) { // 返回成功

                BufferedReader reader = new BufferedReader(

                    new InputStreamReader(httpConn.getInputStream(), "utf-8"));

                String line;

                StringBuffer buffer = new StringBuffer();

                while((line = reader.readLine()) != null) {

                    buffer.append(line).append("/n");

                }

            } else { // 访问失败

                //forward error page

                throw new Exception("Error occur when try to visit the url:" +

                        url.getPath() + " using HttpURLConnection");

            }

        } catch (Exception ex) {

            throw new Exception("Error occur execute " +

                    "HttpRemoteProxy.performImpl(), the caused by " + ex);

        } finally {

            if (httpConn != null)

                httpConn.disconnect();

        }

    }

 

    /*

     * 得到request所有的请求参数,并连接起来

     */

    private StringBuffer getQueryString(HttpServletRequest request)

        throws Exception {

       

        Enumeration paramNames = request.getParameterNames();

        StringBuffer paramData = new StringBuffer();

        while (paramNames.hasMoreElements()) {

            String name = (String)paramNames.nextElement();

            String value = request.getParameter(name);

            value = URLDecoder.decode(value, "utf-8");

            paramData.append(name).append("=").append(value).append("&");

        }

        if (paramData.length() > 0) //delete the last char '&'

            paramData.deleteCharAt(paramData.length() - 1);

        return paramData;

    }

 

    /*

     * 得到所有的cookie,并把它们连接起来

     */

    private String getCookieString(HttpServletRequest request) throws Exception {

        Cookie[] cookies = request.getCookies();

        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < cookies.length; i++) {

            Cookie cookie = cookies[i];

            String value = cookie.getValue();

            String name = cookie.getName();

            if (value != null && !value.equals(""))

                buffer.append(name).append("=").append(value).append(";");

        }

        if (buffer.length() > 0)

            buffer.deleteCharAt(buffer.length() - 1);//delete the last char ';'

        return buffer.toString();

    }

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值