• c# 发送web请求


    我们目前涉及到的现有的接收请求方式有三种,

    第一种:

    页面式的Form表单

    第二种:

    服务的webservice形式的xml

    第三个:

    restful风格的post包体json

    第一种比较老,博客园的登录就是这样的。找了个例子

    这里不做具体讨论了。

    例子

    List<KeyValuePair<string, string>> paramList = new List<KeyValuePair<string, string>>();
                    HttpClient _client = new HttpClient();
    
                    async void DownloadPageAsync()
                    {
                        // Use static HttpClient to avoid exhausting system resources for network connections.
                        var result = await _client.PostAsync(new Uri(url), new FormUrlEncodedContent(paramList));
                        // Write status code.
                        Console.WriteLine("STATUS CODE: " + result.StatusCode);
                        result.EnsureSuccessStatusCode();
                        string resultStr = await result.Content.ReadAsStringAsync();
                        Console.WriteLine(resultStr);
                    }
                    DownloadPageAsync();

    第二种的,webservice的,之前的博客里有。

    参考

    第三种,比较新的json的请求方式

    针对这种,就只能用json字符串来提交了,具体代码是

    string url = getPRC_Url(serviceName, apiName, null);
    string body = "{";
    //如果需要POST数据   
    if (!(parameters == null || parameters.Count == 0))
    {
        StringBuilder buffer = new StringBuilder();
        foreach (string key in parameters.Keys)
        {
            buffer.AppendFormat(""{0}":"{1}",", key, parameters[key]);
        }
        body += buffer.ToString() + "}";
    }
    try
    {
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";
        httpWebRequest.Timeout = 20000;
        byte[] btBodys = Encoding.UTF8.GetBytes(body);
        httpWebRequest.ContentLength = btBodys.Length;
        httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
        HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
        string responseContent = streamReader.ReadToEnd();
        return responseContent;
    }
    catch (Exception ex)
    {
        return null;
    }

    主要是这个入参需要放在包体里,并且得是"{}"形式的方可。

  • 相关阅读:
    The AllegroGraph Tutorial
    Using Prolog withUsing Prolog with AllegroGraph 7.1.0 AllegroGraph 7.1.0
    Prolog 语言入门教程
    Learn Prolog Now!:Chapter 3 Recursion
    What are OWL Ontologies?
    论文阅读:SkillMaN—A skill-based robotic manipulation framework based on perception and reasoning
    论文阅读:Knowledge-based instruction of manipulation tasks for industrial robotics
    Learn Prolog
    KnowRob安装过程中的相关问题记录
    Qt音视频开发17-海康sdk解码
  • 原文地址:https://www.cnblogs.com/Rexcnblog/p/9909799.html
Copyright © 2020-2023  润新知