C#调用URL接口方法

C#跨平台调用接口(URL传参GET调用和Post Json传参调用) 方法一:URL传参POST调用 使用HttpWebRequest,将参数POST调用   string HampsonURL = new BSysConfig().GetValue(ConfigKey.接口地址);                 HampsonInfo Hmodel = new HampsonInfo();                 Hmodel.cname 阅读详情

HttpClient

官方文档HttpClient

get

// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();

static async Task Main()
{
  // Call asynchronous network methods in a try/catch block to handle exceptions.
  try	
  {
     HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
     response.EnsureSuccessStatusCode();
     string responseBody = await response.Content.ReadAsStringAsync();
     // Above three lines can be replaced with new helper method below
     // string responseBody = await client.GetStringAsync(uri);

     Console.WriteLine(responseBody);
  }
  catch(HttpRequestException e)
  {
     Console.WriteLine("\nException Caught!");	
     Console.WriteLine("Message :{0} ",e.Message);
  }
}

post

private readonly HttpClient _httpClient;
public bool Error { get; private set; }
public ProvinceMsgResponse ProvinceMsgResponse { get; private set; }

public async Task OnPost(string url, string postdata, ILogger logger,Action func)
        {
            var client = _httpClient;           
            var httpContent = new StringContent(postdata, Encoding.UTF8, "application/json");
            var response = await client.PostAsync(url, httpContent);

            if (response.IsSuccessStatusCode)
            {
                using (Stream responseStream = await response.Content.ReadAsStreamAsync())
                {
                    responseStream.Position = 0;
                    StreamReader reader = new StreamReader(responseStream);
                    string text = reader.ReadToEnd();
                    ProvinceMsgResponse = JsonConvert.DeserializeObject<ProvinceMsgResponse>(text);
                    if (ProvinceMsgResponse.status != -1 && ProvinceMsgResponse.success == 0)
                    {
                        // 数据库内标识成功
                        logger.LogTrace("跟踪日志");
                        func();
                    }
                    else
                    {
                        logger.LogError("错误日志");
                    }
                }
            }
            else
            {
                Error = true;
                ProvinceMsgResponse = new ProvinceMsgResponse();
            }
        }

转载

第一种方法:

第一步:获取在Web.config中配置要请求的地址
string url = System.Web.Configuration.WebConfigurationManager.AppSettings["url"];
第二步:把字符串编码(编码详解)
 string allStr = System.Web.HttpUtility.UrlEncode(str, System.Text.Encoding.UTF8) ;
第三步:把参数转成byte 
 byte[] bufferB = Encoding.UTF8.GetBytes(allStr);
第四步:构建HttpWebRequest,并发送
System.Net.ServicePointManager.DefaultConnectionLimit = 200;
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = allStr.Length;
Stream PostData = WebReq.GetRequestStream();
PostData.Write(bufferB, 0, bufferB.Length);
PostData.Close();
第五步:接收返回结果(解析返回的JSON)
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
StreamReader sr = new StreamReader(WebResp.GetResponseStream(), System.Text.Encoding.UTF8);
string backstr = sr.ReadToEnd();
backstr = HttpUtility.UrlDecode(backstr);
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
Console.WriteLine(_Answer.ReadToEnd());

第二种方法:

第一步---构建HttpWebRequest
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);               
WebReq.ContentType = "application/json";
WebReq.Method = Method;
第二步--写入参数
 WebReq.ContentLength = Encoding.UTF8.GetByteCount(param);
 using (StreamWriter requestW = new StreamWriter(WebReq.GetRequestStream()))
                     {
                         requestW.Write(param);
                     }
第三步--获取返回的结果
string backstr = null;
using (HttpWebResponse response = (HttpWebResponse)WebReq.GetResponse())
                {
                    StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                    backstr = sr.ReadToEnd();
                }

第三种通用:

public static string MakeRequest(string url, string query_string, string cookie_string, string method, string protocol)
        {
            //cookie
            //string cookie_string = null;
            //if (cookie != null && cookie.Count > 0)
            //{
            //    string[] arr_cookies = new string[cookie.Count];
            //    int i = 0;
            //    foreach (string key in cookie.Keys)
            //    {
            //        arr_cookies[i] = key + "=" + cookie[key];
            //        i++;
            //    }
            //    cookie_string = string.Join("; ", arr_cookies);
            //}
            //结果
            string result = "";
            //请求类
            HttpWebRequest request = null;
            //请求响应类
            HttpWebResponse response = null;
            //响应结果读取类
            StreamReader reader = null;
            //http连接数限制默认为2,多线程情况下可以增加该连接数,非多线程情况下可以注释掉此行代码
            ServicePointManager.DefaultConnectionLimit = 500;
            try
            {
                if (method.Equals("get", StringComparison.OrdinalIgnoreCase))
                {


                    if (url.IndexOf("?") > 0)
                    {
                        url = url + "&" + query_string;
                    }
                    else
                    {
                        url = url + "?" + query_string;
                    }
                    //如果是发送HTTPS请求   
                    if (protocol.Equals("https", StringComparison.OrdinalIgnoreCase))
                    {
                        request = WebRequest.Create(url) as HttpWebRequest;
                        request.ProtocolVersion = HttpVersion.Version10;
                    }
                    else
                    {
                        request = WebRequest.Create(url) as HttpWebRequest;
                    }
                    request.Method = "GET";
                    request.Timeout = 30000;
                }
                else
                {
                    //如果是发送HTTPS请求   
                    if (protocol.Equals("https", StringComparison.OrdinalIgnoreCase))
                    {
                        request = WebRequest.Create(url) as HttpWebRequest;
                        request.ProtocolVersion = HttpVersion.Version10;
                    }
                    else
                    {
                        request = WebRequest.Create(url) as HttpWebRequest;
                    }
                    //去掉“Expect: 100-Continue”请求头,不然会引起post(417) expectation failed
                    ServicePointManager.Expect100Continue = false;


                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Timeout = 30000;
                    //POST数据   
                    byte[] data = Encoding.UTF8.GetBytes(query_string);
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
                //cookie
                if (!string.IsNullOrEmpty(cookie_string))
                {
                    request.Headers.Add("Cookie", cookie_string);
                }
                //response
                response = (HttpWebResponse)request.GetResponse();
                reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                //return
                result = reader.ReadToEnd();
            }
            finally
            {
                if (request != null)
                {
                    request.Abort();
                }
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
            return result;
        }

 

C#分析URL参数并获取参数和值对应列表的方法 本文实例讲述了C#分析URL参数获取参数和值对应列表的方法。分享给大家供大家参考。具体分析如下: 这个C#函数用于分析url中传递的所有参数,输出一个参数名和参数值对应的NameValueCollection列表,经常能用得到 /// <summary> /// 分析 url 字符串中的参数信息 /// </summary> /// <param name=url>输入的 URL</param> /// <param name=baseUrl>输出 URL 的基础部分</param> /// <param name=nvc>输出分析后得到的 (参数名,参数值) 的集合</para 立即下载

相关推荐

ARM 汇编指令:LSL(逻辑左移) 和 LSR(逻辑右移)

ARM 汇编中的 LSL(逻辑左移)和 LSR(逻辑右移)是基础移位指令,分别实现二进制位的左移和右移操作。LSL 低位补0,等效于乘以2^n;LSR 高位补0,等效于无符号除以2^n。这两个指令可以单独使用或与其他指令结合(如ADD、MOV等),利用ARM的"桶形移位器"硬件实现高效运算。关键特性包括:移位范围0-31(LSL)或1-32(LSR),可选更新标志位,以及与其他指令结合时的无额外开销优势。LSR与ASR(算术右移)的主要区别在于高位填充方式,分别适用于无符号和有符号数处理

guigenyi的专栏 1812

c#调用接口的两种方式

1、get请求类型接口调用 public JObject GetDate(string url) { url = RequestIP + url;//比如【http://192.168.xx.xx:1234】 using (var httpClient = new HttpClient()) { ...

墨水直达的博客 1万+

Docker启动安装nacos(详情讲解,全网最细)

docker安装nacos保姆级教程

ilvjiale的博客 8万+

c# 接口使用

接口时指定一组函数成员而不实现它们的引用类型。所以只能类和结构来实现接口。这种描述听起来有点抽象,因此先来看看接口能够解决的问题,以及是如何解决的。以下的代码示例。观察 Program 类中的 Main 方法,它创建并初始化了一个 CA 类的对象,并将该对象传递给 PrintInfo 方法。

qq_50054286的博客 3057

高通camera驱动 camx read xml 和 probe 流程 和 sensor I2C读写的波形图 (三)

Camx 刚接触的时候对于这个xml 一脸懵逼,实际上和mm-camera差不多就是以xml node节点的方式标准化了driver相关的code,exposure 和 gain的逻辑实现还是在同级目录的cpp中,并且将 xml 的解析工作放在了 out/target/<product>/gen/STATIC_LIBERARIES/libcamxgenerated_intermediates/generated/ 中主要是包含了: g_chromatix : tuning 相关xml的解析co

shangbolei的博客 1万+

ADS仿真功率放大器实例学习笔记

ADS仿真功率放大器实例学习笔记

qq_36521926的博客 1万+

c#url拼接方法名_C# Url接口的调用

一般初学者可以百度“聚合数据”,上面都有大量的接口和实例可供参考。。以下是用来调用接口的俩类:/// /// 加载Http请求/// /// /// public static string HttpGet(string Url){HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);request.Method = "G...

weixin_39949297的博客 675

红外弱小目标检测:IPI算法解读及MATLAB复现

参考文献:[1]C. Gaoet al., “Infrared Patch-Image Model for Small Target Detection in a Single Image,” vol. 22, no. 12, pp. 4996–5009, 2013. 本文整理????论文笔记,并附MATLAB实现代码。 一、阅读笔记 1. 摘要 IPI算法是单帧检测算法; 利用背景的非局部子相关性(non-local self-correlation ofbackground),将目标检测转..

小草莓的魔法笔记 1万+

C#调用WebService接口的三种方式

WebService服务端会提供wsdl文件,客户端通过该文件生成.cs文件以及生成.dllPS:注意若是服务端只提供了URL,那可以通过在URL后面加上“?wsdl”在浏览器上访问,复制页面的代码内容,粘贴到文本文件,将文件后缀改为“wsdl”,即可得到wsdl文件。通过URL或wsdl文件都可生成.cs文件。

weixin_38812575的博客 8645

SAP CBC 集成质量系统初始化接入实战指南

摘要 本文探讨了SAP S/4HANA Cloud Public Edition项目中质量系统的初始接入过程。质量系统并非开箱即用,而是需要经过SAP Central Business Configuration(CBC)的Scope and Organizational Structure阶段部署后才能具备完整功能。文章重点分析了几个关键环节:CBC里程碑确认的时机选择、Identity Authentication的初始管理员设置、Business Role Template的创建规范等。实施过程中需特

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1407

浏览器缓存导致代码不更新?一招解决部署后用户仍看到旧页面的问题

方案效果适用场景文件名哈希永久解决前端工程化项目HTTP缓存头控制精准控制需服务器权限Meta标签部分生效临时补救方案最佳实践:入口HTML禁用缓存,静态资源使用哈希文件名 + 长期缓存,达到「秒级更新」+「高性能」的平衡!

江拥羡橙的博客 810

【超细完整版】C# 获取WebService所有方法并调用 【调用篇】

【MintYouth】 C# 获取所有Web Service 方法并进行调用

MintYouth的博客 1898

VMware Horizon 8 2111 部署系列(九)创建即时克隆桌面池

即时克隆桌面池是在 vCenter Server 中使用 vmFork 技术(称为即时克隆 API)从最佳配置映像创建的自动桌面池。即时克隆共享同一个基础映像虚拟机,使用基础映像虚拟机的快照创建的,它使用的存储空间也少于完整虚拟机。 即时克隆始终保持开机状态,并在注销后从当前发布的映像重新创建。...

白昼的技术专栏 4043

axis1 c# 接口 调用_java调用C# webService发布的接口

java调用C# webService发布的接口java调用C# webService方式有很多种我这里只介绍一种首先需要引入axis的jar包 axis的maven坐标如下org.apache.axisaxis1.4下面是调用列子代码:1 //接口地址2 String oaurl =Preferences.getInstance().getOAURL();3 ...

weixin_36336710的博客 205

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

用Java调用WebService接口

这是一个用Java调用C#版WebService接口的例子:C#接口:using System;using System.Web;using System.Web.Services;using System.Web.Services.Protocols;using System.Web.Services.Description;[WebService(Namespace = "http:/

1万+

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

C#使用post方式调用接口获取Token及调用网页地址

C#调用网页 获取Token

j1354223253的博客 7801

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

【转】c#调用webservice接口服务项目代码,引用*.wsdl文件调用

【转】c#调用webservice接口服务项目代码,引用*.wsdl文件调用

yh361的博客 3087

C# 调用服务器接口

请求的接口文档 Url: https://nesting.lyntime.com/optimized_nesting/nesting Method: POST Header: Content-Type:application/json AppKey:填入申请的AppKey Authorization:Bearer token (注意Bearer后有一个空格) Json Body 示例: 下面就是要传递的参数Body { “parts”: [ { “dxf_path”: “dxf/1-y30.dxf”, “p

my_my_heart的博客 1438

C# 创建简单的WebService发布本地和调用方法及环境配置(VS2017)

说明:由于工作的缘故,写MES时遇到了Web的服务接口,想着深入理解web的运作和接口文档文件的生成和调用方法,故写此文章,以备不时之需,共勉。

weixin_50722786的博客 2478

js 访问asmx接口

用C#写了一个接口,js需要用ajax访问 var jsonObj = new Object(); jsonObj['cid'] = cid; $.ajax({ type: "POST", url: "/tv/hub.asmx/getDeviceLogs", data: JSON.string...

ulvge0的博客 1161

[C#/Java] C#中调用Servlet示例

需求 通用消息接口使用servlet作为服务器端服务接口,第三方应用程序通过http post的方式调用servlet,实现与通用消息接口的调用连接。 参数说明如下: msgTitle:消息标题,描述发送消息的标题 serviceId:服务编号,消息的服务编号 msgDesp:消息描述,消息的详细内容 msgURL:URL地址,消息中包含的 URL 上述4个参数的参数值可...

weixin_30865427的博客 101

通过文件反射调用接口

#region 反射自动选择接口地址 /// <summary> /// 缓冲池对象 /// </summary> private static Dictionary<string, ServiceEntity> methodPool = new Dictionary<s...

dcli98004的博客 148

C#动态添加webservice

    //1新建一个类  在程序集里面引用System.Web.Services.dll . //调用方法              string url = "http://webservice.webxml.com.cn/WebServices/TrainTimeWebService.asmx"; //这个是天气的接口             string name ="getWea...

xu1440879014的博客 832

C#后端传model调用webapi的封装

采用Post,将要传给接口的数据封装进对应的model,再调用此函数。 using System; using System.IO; using System.Net; using System.Text; using System.Runtime.Serialization.Json;//4.0.0.0 public static string HttpPost(string Url, ...

GM的博客 877
上一篇: 通过FormData实现上传
下一篇: oracle 分割字符串,转多行
BikeRiver
博客等级 码龄10年 11粉丝 33原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值