日期:2014-05-18 浏览次数:21213 次
URL url = null;
            HttpURLConnection connection = null;
           
            int responseCode = 0;
            String responseMessage = "";
            url = new URL("127.0.0.1:端口号");
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type","对应的类型");
            connection.setRequestProperty("Content-Length",Integer.toString(str.getBytes().length) );
            OutputStream out1=connection.getOutputStream();
            String str=new String("aaaaaaaabbbbbb");
            out1.write(str.getBytes());
            out1.flush();
------解决方案--------------------
用HttpURLConnection发送post请求并获取目标内容,例子如下:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@page import="java.net.URL"%>
<%@page import="java.net.HttpURLConnection"%>
<%@page import="java.io.DataInputStream"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>test</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
    </head>
    <body>
        <%
            URL url = null;
            HttpURLConnection httpurlconnection = null;
            try {
                url = new URL("http://localhost:8080/xxx/testurlto.jsp");
                httpurlconnection = (HttpURLConnection) url.openConnection();
                httpurlconnection.setDoOutput(true);
                httpurlconnection.setRequestMethod("POST");
                String username = "username=aaaaaa";
                httpurlconnection.getOutputStream().write(username.getBytes());
                httpurlconnection.getOutputStream().flush();
                httpurlconnection.getOutputStream().close();
                int code = httpurlconnection.getResponseCode();
                String str = httpurlconnection.getResponseMessage();
                DataInputStream inStream = new DataInputStream(
                        httpurlconnection.getInputStream());
                int ch;
                while ((ch = inStream.read()) >= 0) {
                    System.out.print((char) ch);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (httpurlconnection != null)
                    httpurlconnection.disconnect();
            }
        %>
    </body>
</html>