发送 GET 和 POST 请求
Posted Jacob Wu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了发送 GET 和 POST 请求相关的知识,希望对你有一定的参考价值。
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace Common { public class HttpUtils { /// <summary> /// GET请求与获取结果 /// </summary> public static string HttpGet(string Url, string DataStr) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (DataStr == "" ? "" : "?") + DataStr); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } /// <summary> /// POST请求与获取结果 /// </summary> public static string HttpPost(string Url, string DataStr) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = DataStr.Length; StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII); writer.Write(DataStr); writer.Flush(); 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(); return retString; } } }
以上是关于发送 GET 和 POST 请求的主要内容,如果未能解决你的问题,请参考以下文章
求教golang中http发送post请求gb2312编码的解决方案
iOS开发网络篇—发送GET和POST请求(使用NSURLSession)