• 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;
    }

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

  • 相关阅读:
    证明 O(n/1+n/2+…+n/n)=O(nlogn)
    ZOJ 3623 Battle Ships DP
    ZOJ 3631 Watashi's BG DFS
    ZOJ 3622 Magic Number 打表找规律
    poj 1088 滑雪 记忆化搜索
    poj 1273 Drainage Ditches 网络流最大流基础
    Codeforces Round #243 (Div. 1)A. Sereja and Swaps 暴力
    UVALive 5059 C
    Codeforces Round #295 (Div. 2)C
    Codeforces Round #295 (Div. 2)B
  • 原文地址:https://www.cnblogs.com/Rexcnblog/p/9909799.html
Copyright © 2020-2023  润新知