• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#HTTP请求

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;

request.Method = "POST";

request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

request.Headers.Add("Cookie", "JSESSIONID=F281A192223C6B2D4D1256BD40495194");  // cookie  要这么加 

request.Referer = "http://192.168.222.203:8080/************/user_register.do?P=op_register&latest=102001";  

request.Host = "192.168.222.203:8080";

//在写入流之前 把所有的设置写好

string data1 = "userId=7c509e59-9179-4fc3-b00a-a33007b1068e&agentId=2acbf00f-aa58-44f6-88c8-6d7027b78a7f&companyId=64436ad0-8ef4-430a-b6a4-08cac3b19c0a&versionTime=0";

//如果是传的json 就用转义符拼接起来 如下:

//string data = "{\"ActualStartTime\":\"2020-04-08 12:12:04\",\"FinishDate\":\"2020-04-08 12:12:04\",\"FinishRemark\":\"完成情况说明\",\"CompleteRate\":100,\"PlanTaskExecuteGUID\":\"cdf1c2df-1741-41a4-b809-08d7bb58c553\",\"FilePath\":\"成果文件物理路径\"}";
//byte[] bytes = Encoding.UTF8.GetBytes(data);

  

byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data1);
request.ContentLength = buf.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(buf, 0, buf.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
string result = reader.ReadToEnd();

 

            string url = "http://192.168.222.203:8080/************/operation.do";   
            HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            request.Headers.Add("Accept-Encoding", "gzip,deflate");
            request.Headers.Add("cache-control", "no-cache");
            request.Headers.Add("Cookie", "JSESSIONID=F281A192223C6B2D4D1256BD40495194");
            request.Referer = "http://192.168.222.203:8080/************/user_register.do?P=op_register&latest=102001";
            request.Host = "192.168.222.203:8080";
            byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
            request.ContentLength = buf.Length;
            Stream newStream = request.GetRequestStream();
            newStream.Write(buf, 0, buf.Length);
            newStream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
            string result = reader.ReadToEnd();
            dynamic results = JsonConvert.DeserializeObject(result);

 

 

get中 url把参数a=1&b=2 这种匹配好

HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;

request.Method = "GET";

request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

CookieContainer cookie = new CookieContainer();

request.CookieContainer = cookie;// cookie  要这么加 

request.Referer = "http://192.168.222.203:8080/************/user_register.do?P=op_register&latest=102001";  

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
string result = reader.ReadToEnd();

            string url = "http://192.168.222.203:8080/************/user_query.do?P=queryUsers&_dc=1537359997086";
            url = url + "&" + "judgeClause=&judgeClauseTotalRecords=237&includeDeleteUsers=false&page=1&start=0&limit=50";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            CookieContainer cc = new CookieContainer();
            cc.Add(new Cookie("JSESSIONID", "F281A192223C6B2D4D1256BD40495194", "/DrcomManager", "192.168.222.203"));
            request.Referer = " http://192.168.222.203:8080/************/user_query.do?P=openlistdata&latest=101000";
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            request.CookieContainer = cc;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();

细心看的话 两者的cookie的增加方式是有区别的  只是看你喜欢哪一种方式都可以

CookieContainer cookie = new CookieContainer();

request.CookieContainer = cookie;

request.Headers.Add("Cookie", "JSESSIONID=F281A192223C6B2D4D1256BD40495194");

 

 

=======================================================2020年3月16日再次编辑=======================================================

使用HttpClient来进行http请求  


    class Program
    {
        static void Main(string[] args)
        {
            string _accessToken = "";
            new Task(async () =>
            {
                _accessToken = await GetAccessTokenAsync();
                Console.WriteLine(_accessToken);
            }).Start();
            Console.ReadKey();
        }
        public static async Task<string> GetAccessTokenAsync()
        {
            string clientId = "********";
            string clientSecret = "********";
            string _accessToken = "";
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                "Basic",
                Convert.ToBase64String(Encoding.ASCII.GetBytes(clientId + ":" + clientSecret))
                );
            //var parameters = new Dictionary<string, string>();
            //parameters.Add("grant_type", "client_credentials");
            //var content = new FormUrlEncodedContent(parameters);
            var content = new FormUrlEncodedContent(new Dictionary<string, string>() { { "grant_type", "client_credentials" } });
            var response = await client.PostAsync("http://localhost:5888/Authorize", content);
            var responseValue = await response.Content.ReadAsStringAsync();
            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return string.Empty;

            }
            _accessToken = JObject.Parse(responseValue)["access_token"].Value<string>();
            return _accessToken;
        }
    }

另外还有WebClient 还有一个

很简单 就不过多阐述了

WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8; //设置按照何种编码访问,如果不加此行,获取到的字符串中文将是乱码
string str = wc.DownloadString("url");  

==================================================

当HttpWebRequest 出错时获取相应的Response信息  

这一解决方案转载于:https://blog.csdn.net/m0_37655585/article/details/107312824

HttpWebResponse response;
try
{
response = (HttpWebResponse)webReq.GetResponse();
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
}
//在这里对接收到的页面内容进行处理
using (StreamReader sr = new StreamReader(response.GetResponseStream(), encoding))
{
responseContent = sr.ReadToEnd().ToString();
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# 连接ACCESS数据库代码实例发布时间:2022-07-13
下一篇:
C++文件流发布时间:2022-07-13
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap