用java代码实现Post请求

转载自:传智播客教程

public static boolean sendPostRequest(String path, Map<String, String> params, String enc) throws Exception{
        // title=dsfdsf&timelength=23&method=save
        StringBuilder sb = new StringBuilder();
        if(params!=null && !params.isEmpty()){
            for(Map.Entry<String, String> entry : params.entrySet()){
                sb.append(entry.getKey()).append('=')
                    .append(URLEncoder.encode(entry.getValue(), enc)).append('&');
            }
            sb.deleteCharAt(sb.length()-1);
        }
        byte[] entitydata = sb.toString().getBytes();//得到实体的二进制数据
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(5 * 1000);
        conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据
        //Content-Type: application/x-www-form-urlencoded
        //Content-Length: 38
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length));
        
        OutputStream outStream = conn.getOutputStream();
        outStream.write(entitydata);
        outStream.flush();
        outStream.close();
        if(conn.getResponseCode()==200){
            return true;
        }
        return false;
    }

服务端使用struts技术:

public ActionForward save(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        VideoForm formbean = (VideoForm)form;
        if("GET".equals(request.getMethod())){
            byte[] data = request.getParameter("title").getBytes("ISO-8859-1");
            String title = new String(data, "UTF-8");
            System.out.println("title:"+ title);
            System.out.println("timelength:"+ formbean.getTimelength());
        }else{
            System.out.println("title:"+ formbean.getTitle());
            System.out.println("timelength:"+ formbean.getTimelength());
        }
        return mapping.findForward("result");
    }

 

调用示例:

public void testSendPostRequest() throws Throwable{
        Map<String, String> params = new HashMap<String, String>();
        params.put("method", "save");
        params.put("title", "中国");
        params.put("timelength", "80");
        
        HttpRequest.sendPostRequest("http://10.10.97.51:8180/videoweb/video/manage.do", params, "UTF-8");
    }

 

posted @ 2016-04-14 09:53  进进  阅读(2153)  评论(0)    收藏  举报