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