URLConnection 模拟浏览器向服务器提交数据,服务器返回数据

新建一个web project,项目名为test,很简单,只有一个登陆功能。

只有两个html页面,login.html和success.html。

login.html:

<form action="login" method="post">
    <table>
    <tr>
    <td>用户名:</td>
    <td><input name="userName" type="text"/></td>
    </tr>
    <tr>
    <td>密码:</td>
    <td><input name="passWord" type="text"/></td>
    </tr>
    <tr>
    <td><input type="submit" value="登陆"/></td>
    <td></td>
    </tr>
    </table>
    </form>

success.html:

就是new了一个html,仅供登陆成功跳转使用。


一个servlet,LoginServlet。


public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);

}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getParameter("userName");
String passWord = request.getParameter("passWord");
if (userName.equals("admin") && passWord.equals("pwd")) {
request.getRequestDispatcher("success.html").forward(request, response);
}
}


}


配置文件web.xml:

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.login.LoginServlet</servlet-class>
 </servlet>

<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
 </servlet-mapping>



<welcome-file-list>
    <welcome-file>login.html</welcome-file>
 </welcome-file-list>

输入  http://localhost:8080/test/   即是login.html。


用户名和密码输入正确即跳转到success.html页面。

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;


public class HttpPostRequest {
/**
     * Main
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        System.out.println(doPost());
    }
    
    /**
     * Post Request
     * @return
     * @throws Exception
     */
    public static String doPost() throws Exception {
    //向服务器传递的参数字符串
    String postParams =
                new StringBuilder("userName=").append("admin").append("&passWord=").append("pwd")
                        .toString();
    //1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)
    URL url = new URL("http://localhost:8080/test/login");
    URLConnection connection = url.openConnection();
    //2.设置请求的参数
    connection.setConnectTimeout(1000 * 30);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
    //向服务器写入数据
    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    out.write(postParams.getBytes("UTF-8"));
    out.close();
    //读取服务器返回的数据
    BufferedReader in =
                new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        StringBuilder resStr = new StringBuilder();
        String s = "";
        while ((s = in.readLine()) != null)
            resStr.append(s);
        in.close();
   
        String data = resStr.toString();
        data = URLDecoder.decode(data, "utf-8");


        return data;
    }
}

运行即可输出success.html的页面代码。如果想要返回字符串,可将success.html的页面代码全部删除。在servlet中写入要返回的字符串即可。

如下所示:

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getParameter("userName");
String passWord = request.getParameter("passWord");
if (userName.equals("admin") && passWord.equals("pwd")) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("测试一下");
out.flush();
out.close();
request.getRequestDispatcher("success.html").forward(request, response);
}
}


你可能感兴趣的:(URLConnection 模拟浏览器向服务器提交数据,服务器返回数据)