C# 使用HttpWebRequest 实现简单的get和post请求和服务器进行交互
刚刚学会的,用的也是最简单的方法,实现了一个登陆功能
下面记录一下我自己理解
首先我们要实现的是模拟浏览器的登陆功能,那么就要知道浏览器是怎么和服务器进行交互的。
这里为了方便,我自己搭建了一个只有登陆功能的小页面
我这里用的是Firefox浏览器,按F12就可以打开下面的监视的工具
点击登陆之后,发现浏览器是通过POST请求向浏览器发送登陆请求
查看参数,就可以看到,我们在登陆的时候填的账号和密码。
好了,我们了解了浏览器的请求过程后,下面就通过代码来模拟浏览器,来实现一个登陆过程
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.IO;
- using System.Net;
- using System.Text;
-
- namespace WindowsFormsApplication1
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- private void button1_Click(object sender, EventArgs e)//模拟GET请求
- {
- String url = "http://。。。。。/LoginTest/login?username=admin&password=123456";//请求的链接,为了方便直接填上了后面的参数
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- request.Method = "GET";
- request.Accept = "*/*";
- HttpWebResponse response = (HttpWebResponse)request.GetResponse();
- Stream getStream = response.GetResponseStream();
- StreamReader streamreader = new StreamReader(getStream);
- String result = streamreader.ReadToEnd();
- label1.Text = result;
- }
-
- private void button2_Click(object sender, EventArgs e)
- {
- String url = "http://。。。。。/LoginTest/login";
- HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
- req.Method = "POST";
- req.ContentType = "application/x-www-form-urlencoded";//设置对应的ContentType
- String postdata = "username=admin&password=123456";//post请求时的参数
- StreamWriter writer = new StreamWriter(req.GetRequestStream());
- writer.Write(postdata);
- writer.Flush();
-
- HttpWebResponse response = (HttpWebResponse)req.GetResponse();//获取服务器返回的结果
- Stream getStream = response.GetResponseStream();
- StreamReader streamreader = new StreamReader(getStream);
- String result = streamreader.ReadToEnd();
- label2.Text = result;
- }
- }
- }
服务器端用的是Java写的动态网站使用Tomcat部署
创建一个LoginServlet类继承自HtteServlet
- package login;
- import java.io.IOException;
- import java.io.PrintWriter;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import org.apache.coyote.Response;
-
-
- public class LoginServlet extends HttpServlet{
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- resp.setContentType("text/html;charset=UTF-8");
- String username=req.getParameter("username");
- String password=req.getParameter("password");
- String result="fail";
- if(username.equals("admin") && password.equals("123456")){
- result="成功";
- }
- PrintWriter outPrintWriter=resp.getWriter();
- outPrintWriter.write(result);
- }
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- doGet(req, resp);
- }
- }