ajax 调用接口 C# 调用接口 PostHttpResponse 类

前端之家收集整理的这篇文章主要介绍了ajax 调用接口 C# 调用接口 PostHttpResponse 类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

----------------------------------------------------------------- ajax 调用接口---------------------------------------------------

<script type="text/javascript">

$(document).ready(function () {
$.ajax({
//提交数据的类型 POST GET
type: "POST",
//提交的网址
url: "http://localhost:8088/test/",
//提交的数据
data: '{ "interface": "interface_test","type": "web","ver": 1,"uid": "test","pwd": "123456" }',
//返回数据的格式
datatype: "json",//"xml","html","script","json","jsonp","text".
//在请求之前调用函数
//beforeSend: function () {
// // $("#msg").html("logining");
// alert(1);
//},
//成功返回之后调用函数
success: function (data) {
alert(decodeURI(data));
alert(data.err);
alert(data.error);
},
//调用执行后调用函数
complete: function (XMLHttpRequest,textStatus) {
},
//调用出错执行的函数
error: function () {
//请求出错处理
alert(0);
}
});
});

</script>

-----------------------------------------------------------------End---------------------------------------------------

----------------------C#-------------------------------------

调用接口的方法

/// <summary>
/// /post方法调用接口获取json文件内容
/// </summary>
static void ReadMethod2(string url,string pars)
{
string serviceAddress = url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);


request.Method = "POST";
request.ContentType = "application/json";
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
{
dataStream.Write(pars);
dataStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(),Encoding.GetEncoding(encoding));
string retString = reader.ReadToEnd();


Console.WriteLine(retString);//在控制台输入获取内容
}

-----------------------接口调用的地方--------------------------------------------------------------------------------------------------------------------------------------------------------

static void Main(string[] args)
{
string url1 = "http://localhost:8088/test/";
string pars1 = File.ReadAllText("D:\\WorkSpace\\Test\\json_test.txt",Encoding.Default);


string result = PostHttpResponse.PostHttpResponseJson(url1,pars1);
Console.WriteLine(result);


string url = "http://localhost:8088/test/";
string pars = @"{ ""interface"": ""interface_test"",""type"": ""web"",""ver"": 1,""uid"": ""test"",""pwd"": ""123456""}";
ReadMethod2(url,pars);
Console.Read();
}

-----------------------PostHttpResponse 类--------------------------------------------------------------------------------------------------------------------------------------------------------

using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace ConsoleApplicationTest { public class PostHttpResponse { #region Static Field private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; #endregion #region public Method public static string PostHttpResponseJson(string url) { string json = string.Empty; Encoding encoding = Encoding.UTF8; HttpWebResponse Response = CreatePostHttpResponseJson(url,null,encoding,null); json = GetStream(Response,encoding); return json; } public static string PostHttpResponseJson(string url,string postJson) { string json = string.Empty; Encoding encoding = Encoding.UTF8; HttpWebResponse Response = CreatePostHttpResponseJson(url,postJson,encoding); return json; } /// <summary> /// 创建POST方式Json数据的HTTP请求(包括了https站点请求) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">随同请求POST的参数名称及参数值字典</param> /// <param name="timeout">请求的超时时间</param> /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param> /// <param name="requestEncoding">发送HTTP请求时所用的编码</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param> /// <returns></returns> public static HttpWebResponse CreatePostHttpResponseJson(string url,string postJson,string parameters,int? timeout,string userAgent,Encoding requestEncoding,string referer) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } if (requestEncoding == null) { throw new ArgumentNullException("requestEncoding"); } HttpWebRequest request = null; //如果是发送HTTPS请求 if (url.StartsWith("https",StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; } else { request = WebRequest.Create(url) as HttpWebRequest; } request.Method = "POST"; //服务端 判断 客户端 提交的是否是 JSON数据 时 request.ContentType = "application/json;charset=UTF-8"; request.KeepAlive = true; if (!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } else { request.UserAgent = DefaultUserAgent; } if (timeout.HasValue) { request.Timeout = timeout.Value; } //如果需要POST数据 #region post parameter 类似querystring格式 if (parameters != null) { byte[] data = requestEncoding.GetBytes(parameters); using (Stream stream = request.GetRequestStream()) { stream.Write(data,data.Length); stream.Close(); } } #endregion #region post json if (!string.IsNullOrEmpty(postJson)) { using (var streamWriter = new StreamWriter(request.GetRequestStream())) { //string json = "{\"user\":\"test\"," + // "\"password\":\"bla\"}"; streamWriter.Write(postJson); streamWriter.Flush(); streamWriter.Close(); } } #endregion if (!string.IsNullOrEmpty(referer)) { request.Referer = referer; } HttpWebResponse response = request.GetResponse() as HttpWebResponse; if (request.CookieContainer != null) { response.Cookies = request.CookieContainer.GetCookies(request.RequestUri); } return response; } #endregion #region Private Method private static bool CheckValidationResult(object sender,X509Certificate certificate,X509Chain chain,SslPolicyErrors errors) { return true; //总是接受 } /// <summary> /// 将response转换成文本 /// </summary> /// <param name="response"></param> /// <param name="encoding"></param> /// <returns></returns> private static string GetStream(HttpWebResponse response,Encoding encoding) { try { if (response.StatusCode == HttpStatusCode.OK) { switch (response.ContentEncoding.ToLower()) { case "gzip": { string result = Decompress(response.GetResponseStream(),encoding); response.Close(); return result; } default: { using (StreamReader sr = new StreamReader(response.GetResponseStream(),encoding)) { string result = sr.ReadToEnd(); sr.Close(); sr.Dispose(); response.Close(); return result; } } } } else { response.Close(); } } catch (Exception e) { throw e; } return ""; } private static string Decompress(Stream stream,Encoding encoding) { byte[] buffer = new byte[100]; //int length = 0; using (GZipStream gz = new GZipStream(stream,CompressionMode.Decompress)) { //GZipStream gzip = new GZipStream(res.GetResponseStream(),CompressionMode.Decompress); using (StreamReader reader = new StreamReader(gz,encoding)) { return reader.ReadToEnd(); } /* using (MemoryStream msTemp = new MemoryStream()) { //解压时直接使用Read方法读取内容,不能调用GZipStream实例的Length等属性,否则会出错:System.NotSupportedException: 不支持此操作; while ((length = gz.Read(buffer,buffer.Length)) != 0) { msTemp.Write(buffer,length); } return encoding.GetString(msTemp.ToArray()); } * */ } } #endregion /// <summary> /// 创建POST方式的HTTP请求 /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">随同请求POST的参数名称及参数值字典</param> /// <param name="timeout">请求的超时时间</param> /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param> /// <param name="requestEncoding">发送HTTP请求时所用的编码</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param> /// <returns></returns> public static HttpWebResponse CreatePostHttpResponse(string url,IDictionary<string,string> parameters,CookieCollection cookies) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } if (requestEncoding == null) { throw new ArgumentNullException("requestEncoding"); } HttpWebRequest request = null; //如果是发送HTTPS请求 if (url.StartsWith("https",StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; } else { request = WebRequest.Create(url) as HttpWebRequest; } request.Method = "POST"; request.Headers.Add("X_REG_CODE","288a633ccc1"); request.Headers.Add("X_MACHINE_ID","a306b7c51254cfc5e22c7ac0702cdf87"); request.Headers.Add("X_REG_SECRET","de308301cf381bd4a37a184854035475d4c64946"); request.Headers.Add("X_STORE","0001"); request.Headers.Add("X_BAY","0001-01"); request.Headers.Add("X-Requested-With","XMLHttpRequest"); request.ContentType = "application/x-www-form-urlencoded"; request.Headers.Add("Accept-Language","zh-CN"); request.Headers.Add("Accept-Encoding","gzip,deflate"); request.Accept = "*/*"; if (!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } else { request.UserAgent = DefaultUserAgent; } if (timeout.HasValue) { request.Timeout = timeout.Value; } // if (cookies != null) // { request.CookieContainer = new CookieContainer(); // request.CookieContainer.Add(cookies); // } //如果需要POST数据 if (!(parameters == null || parameters.Count == 0)) { StringBuilder buffer = new StringBuilder(); int i = 0; foreach (string key in parameters.Keys) { if (i > 0) { buffer.AppendFormat("&{0}={1}",key,parameters[key]); } else { buffer.AppendFormat("{0}={1}",parameters[key]); } i++; } byte[] data = requestEncoding.GetBytes(buffer.ToString()); using (Stream stream = request.GetRequestStream()) { stream.Write(data,data.Length); } } HttpWebResponse res; try { res = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { res = (HttpWebResponse)ex.Response; } return res; } } }

原文链接:https://www.f2er.com/ajax/162309.html

猜你在找的Ajax相关文章