在给一些客户端做服务器端支持时,发现他们提交上来的数据大都不是http请求格式,因而使用Request.Form获取不到内容,今天用C#做下模拟,并演示下数据接收。

1.发送文本

1).客户端发送文本

using System;
using System.IO;
using System.Net;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Post("http://localhost/Test", "木子屋", Encoding.UTF8));
            Console.ReadKey();
        }

/// <summary>
        /// 发送文本
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string Post(string url, string data, Encoding encoding)
        {
            byte[] bytes = encoding.GetBytes(data);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentLength = bytes.Length;
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(bytes, 0, bytes.Length);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader stream = new StreamReader(response.GetResponseStream(), encoding))
            {
                return stream.ReadToEnd();
            }
        }
    }
}

2).服务器端接收文本

string str = "";
using (StreamReader stream = new StreamReader(Request.InputStream))
{
    str = stream.ReadToEnd();
}

说明:只需增加request.ContentType = "application/x-www-form-urlencoded",并将文本格式改为"data=木子屋",服务器端即可用Request.Form["data"]接收。

2.上传文件

1).客户端上传文件

using System;
using System.IO;
using System.Net;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(UploadFile("http://localhost/Test", @"E:\test.jpg"));
            Console.ReadKey();
        }

/// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string UploadFile(string url, string file)
        {
            //1.HttpWebRequest
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            using (Stream stream = request.GetRequestStream())
            {
                using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
                {
                    byte[] buffer = new byte[4096];
                    int bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        stream.Write(buffer, 0, bytesRead);
                    }
                }
            }
            //2.HttpWebResponse
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return stream.ReadToEnd();
            }
        }
    }
}

2).服务器端接收文件

using (FileStream file = System.IO.File.Create(Request.MapPath("test.jpg")))
{
    using (BinaryReader stream = new BinaryReader(Request.InputStream))
    {
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
        {
            file.Write(buffer, 0, bytesRead);
        }
    }
}
 

C#模拟客户端发送数据示例的更多相关文章

  1. SSH服务器与Android通信(3)--Android客户端发送数据

    Android客户端向SSH服务器发送数据主要有三种情况:通过客户端删除数据.添加数据和修改数据. 1.删除数据 先看看jsp文件里面是怎样删除数据的: <td align="cent ...

  2. server-sent-event使用流信息向客户端发送数据

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. TCP实现多个客户端发送数据给服务器端

    SocketThread给服务端用的线程类: public class SocketThread extends Thread{ private Socket socket; public Socke ...

  4. kafka模拟客户端发送、接受消息

    producer   消息的生成者,即发布消息 consumer   消息的消费者,即订阅消息 broker     Kafka以集群的方式运行,可以由一个或多个服务组成,服务即broker zook ...

  5. 利用EL表达式+JSTL在客户端取得数据 示例

    <%@page import="cn.gbx.domain.Address"%> <%@page import="cn.gbx.domain.User& ...

  6. linux上kafka模拟客户端发送、接受消息

    producer   消息的生成者,即发布消息 consumer   消息的消费者,即订阅消息 broker     Kafka以集群的方式运行,可以由一个或多个服务组成,服务即broker zook ...

  7. android socket 通讯(客户端) 发送数据

    /** ClientSocket通讯类 **/  public class ClientSocket  {     /**服务器地址*/     private String serverUrl=&q ...

  8. python使用socket向客户端发送数据的方法

    在使用locust测试长连接的时候,所有的请求全部faillure了,所以想到手动写一个连接脚本测试一下是否能连通 因为centos7自带python2.7所以用python写一个比较方便. #!/u ...

  9. Http协议以及模拟http请求发送数据

    1 为什么要使用http协议 假设我现在有两个客户端浏览器,一个是google,一个是IE浏览器:我现在有两个服务器,一个是tomcat,一个是JBoss;在最初的情况下是:如果google要往tom ...

随机推荐

  1. react-route4 学习记录

    新建项目 create-react-app react20180413 安装路由 npm install react-router-dom -S 跑通路由 删除全部文件后 重新新建index.js 代 ...

  2. hive提前过滤重要性

    hive提前过滤 create table sospdm.tmp_yinfei_test_01 ( id string ) partitioned by (statis_date string) ; ...

  3. 线段树-hdu3397

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3397 题目描述: 题目大意:给我们一串二进制串,需要我们对其进行以下操作: 1.输入0,a,b,将a, ...

  4. Java 之 Web前端(一)

    1.http a.定义:超文本传输协议 b.作用:web服务器与web浏览器之间通信 c.步骤: ①客户端与web服务器建立连接(IP地址与端口号) ②客户端发送http请求(请求资源路径) ③服务器 ...

  5. Xamarin Essentials教程陀螺仪Gyroscope

    Xamarin Essentials教程陀螺仪Gyroscope   陀螺仪是用来检测设备在X.Y.Z轴上所旋转的角速度.应用程序通过陀螺仪可以获取设备在各个方向的转动角速度,可以实现更为丰富的控制功 ...

  6. Jmeter测试http+JSON配置相关

    1.添加HTTP信息头管理器 Content-Type application/json Accept application/json 2.添加http请求(方法.编码.路径.body)

  7. [Python]Marshmallow 代码

    schema.dump和schema.load schema.dump()方法返回一个MarshResult的对象,marshmallow官方API说dump和load方法返回的都是dict对象,但查 ...

  8. Java笔记(六)列表和队列

    列表和队列 一)ArrayList 1.基本原理 ArrayList是一个泛型容器.内部会有一个数组elementData,一般会有预留空间 有一个整数记录实际的元素个数. private trans ...

  9. STM32——C语言课堂原代码

    指针 /* ============================================================================ Name : Hello.c Au ...

  10. vue中,class与style绑定

    <template> <div> <p v-bind:class="{active:isActive,'demo':Demo}">嘿嘿</ ...