您的位置:首页 > 理论基础 > 计算机网络

C# 实现HTTP POST请求与接收响应

2015-12-30 23:06 393 查看
用C#实现HTTP请求比较容易实现。根据网上的程序修改而成,实现代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace HTTP_Request_V1
{
public partial class Http_Post : Form
{
public Http_Post()
{
InitializeComponent();
}

private void btn_Go_Click(object sender, EventArgs e)
{
string postData = "username=" + txt_User.Text + "&password=" + txt_Pwd.Text;
postData += ("&vcode=" + txt_VCode.Text);
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);
string url = txt_Url.Text;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
webRequest.Method = "POST";             //POST
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();

HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
txt_Response.Text = sr.ReadToEnd();
}

private void Form1_Load(object sender, EventArgs e)
{
txt_Url.Text = "http://fsmd.vicp.net:22279/PHP_001/hello2/index5.php";
txt_User.Text = "Boy";
txt_Pwd.Text = "12345";
txt_VCode.Text = "admin";
}
}
}


为了测试,自己搭了一个简单的WEB服务器,使用PHP编程。代码如下:

index5.php


<?php
header("content-Type: text/html; charset=Utf-8");
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2015/12/5
* Time: 21:37
*/

@$user = $_POST['username'];
@$pass =$_POST['password'];
@$vcode=$_POST['vcode'];
echo "用户名=$user";
echo "|密码=$pass";
echo "|验证码=$vcode";
?>


程序运行结果如下:



工程下载:点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: