post&get请求总结

1.将get获取的数据,UrlDecode后返回

public static string SendGet(string url)
{
  HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
  httpWebRequest.Method = "GET";
  HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
  Stream stream = httpWebResponse.GetResponseStream();
  StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
  string strOut = streamReader.ReadToEnd();
  httpWebResponse.Close();
  strOut = HttpUtility.UrlDecode(strOut);
  return strOut;
}

2.post请求,StreamReader方法获取ResponseStream中的信息

public static string SendPost(string data, string url, string contentType)
{
  string content = string.Empty;
  HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
  httpWebRequest.AllowAutoRedirect = true;
  httpWebRequest.Method = "POST";
  httpWebRequest.ContentType = contentType;
  using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
  {
    sw.Write(data);
  }
  HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
  using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
  {
    content = sr.ReadToEnd();
  }
  return content;
}

3.post请求,通过Stream.Read方法获取ResponseStream中的信息

post&get请求总结

 public static String RequestUrl(String url, byte[] data, String method = "POST")
{
try
{
  WebRequest request = WebRequest.Create(url);
request.Method = method;
request.ContentType = "application/x-www-form-urlencoded";
if (data != null && data.Length > )
{
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(data, , data.Length);
newStream.Close();
}
else
{
request.ContentLength = ;
}
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
MemoryStream ms = new MemoryStream();
long ChunkSize = ;
byte[] buffer = new byte[ChunkSize];
long dataLengthToRead = response.ContentLength;//获取响应数据的总大小
while (dataLengthToRead > )
{
int lengthRead = stream.Read(buffer, , Convert.ToInt32(ChunkSize));//读取的大小
ms.Write(buffer, , lengthRead);
dataLengthToRead = dataLengthToRead -
lengthRead;
}

stream.Close();
response.Close();
string responseText = Encoding.UTF8.GetString(ms.ToArray());
return responseText;
}
catch (Exception ex)
{
return ex.Message;
}
}
上一篇:iOS开发——数据持久化Swift篇&通用文件存储


下一篇:Qt Model/View(官方翻译,图文并茂)