C# http完整客户端(webform)实例演示


1 . 新建http 客户端处理类HttpUitls.cs  该类指定放在webform 网站项目 App_Code文件夹下

 using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net;

using System.Text;

using System.Threading.Tasks;

 

namespace Http_客户1

{

    public class HttpUitls

    {

        public static string Get(string Url)

        {

            //System.GC.Collect();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

            request.Proxy = null;

            request.KeepAlive = false;

            request.Method = "GET";

            //request.ContentType = "application/json; charset=UTF-8";

            request.ContentType = "application/x-www-form-urlencoded";//窗体数据被编码为名称/值对形式

            request.AutomaticDecompression = DecompressionMethods.GZip;

 

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream myResponseStream = response.GetResponseStream();

            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);

            string retString = myStreamReader.ReadToEnd();

 

            myStreamReader.Close();

            myResponseStream.Close();

 

            if (response != null)

            {

                response.Close();

            }

            if (request != null)

            {

                request.Abort();

            }

 

            return retString;

        }

        /// <summary>

        /// Post请求可用

        /// </summary>

        /// <param name="Url"></param>

        /// <param name="Data"></param>

        /// <param name="Referer"></param>

        /// <returns></returns>

        public static string Post(string Url, string Data, string Referer)

        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

            request.Method = "POST";

            request.Referer = Referer;

            //request.Proxy = new WebProxy("192.168.1.12",80);

            byte[] bytes = Encoding.UTF8.GetBytes(Data);

            request.ContentType = "application/json; charset=UTF-8"; ;//窗体数据被编码为名称/值对形式

            //request.ContentType = "application/json";

            request.ContentLength = bytes.Length;

            Stream myResponseStream = request.GetRequestStream();

            myResponseStream.Write(bytes, 0, bytes.Length);

 

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

            string retString = myStreamReader.ReadToEnd();

            //Task<string> retString = myStreamReader.ReadToEndAsync();

 

            myStreamReader.Close();

            myResponseStream.Close();

 

            if (response != null)

            {

                response.Close();

            }

            if (request != null)

            {

                request.Abort();

            }

            return retString.ToString();

        }

 

    }

 

}

 

2 前端页面代码,Index.aspx 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Index.aspx.cs" Inherits="Index" %>

 

<!DOCTYPE html>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>测试网站</title>

    <script src="JS/jquery.min.js"></script>

    <script src="JS/jquery-2.1.1.js"></script>

 

    <script type="text/javascript">

        $(function () {

            $("#btn1").click(function () {

                var txtparam1 = $("#txtParam1").val();

                var txtparam2 = $("#txtParam2").val();

                $.ajax({

                    url: "Index.aspx/AjaxMethod",//发送到本页面后台AjaxMethod方法

                    type: "POST",

                    dataType: "json",

                    async: true,//async翻译为异步的,false表示同步,会等待执行完成,true为异步

                    contentType: "application/json; charset=utf-8",//不可少

                    data: "{param1:'" + txtparam1 + "',param2:'" + txtparam2 + "'}",

                    success: function (data) {

                        $("#result").html(data.d);

                    },

                    error: function () {

                        alert("请求出错处理");

                    }

                });

                

            });

        });

    </script>

</head>

<body>

    <form id="form1" runat="server">

        参数1:<input type="text" id="txtParam1" value="" /><br />

        参数2:<input type="text" id="txtParam2" value="" /><br />

        <input type="button" id="btn1" value="提交" /><br />

        <div id="result"></div>

    </form>

</body>

</html>

3 . 页面后台代码 Index.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using Http_客户1;

using Entities;

using System.Configuration;

 

 

public partial class Index : System.Web.UI.Page

{

    protected static string _Url = ConfigurationManager.ConnectionStrings["url"]==null ? "http://127.0.0.1:1500/Service/" : ConfigurationManager.ConnectionStrings["url"].ToString();

 

 

    protected void Page_Load(object sender, EventArgs e)

    {

        

    }

 

    public string GetResult()

    {

        return "";

    }

 

    /// <summary>

    /// type方式必须是post,方法必须是静态的,方法声明要加上特性[System.Web.Services.WebMethod()],传递的参数个数也应该和方法的参数相同。

    /// </summary>

    /// <param name="param1"></param>

    /// <param name="param2"></param>

    /// <returns></returns>

    [System.Web.Services.WebMethod()]

    public static  string AjaxMethod(string param1, string param2)

    {

        List<LoginInfo> loginInfos = new List<LoginInfo>() { new LoginInfo() { LoginName = param1, PassWord = param2 } };

        string parames = Newtonsoft.Json.JsonConvert.SerializeObject(loginInfos);

        ///http请求远程服务器

        var result = HttpUitls.Post(_Url, parames, null);

        return result;

    }

 

}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM