在项目中会碰到需要调用网址get或者post数据的情况,下面就贴下我常用的方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using LitJson;
namespace Common
{
public class THttp
{
public static string GetHtml(string URL)
{
try
{
WebRequest wrt;
wrt = WebRequest.Create(URL);
wrt.Credentials = CredentialCache.DefaultCredentials;
WebResponse wrp;
wrp = wrt.GetResponse();
string reader = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
wrt.GetResponse().Close();
return reader;
}
catch (WebException ex)
{
throw ex;
}
}
public static string PostData(string RequestPara, string Url)
{
WebRequest hr = HttpWebRequest.Create(Url);
byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(RequestPara);
hr.ContentType = "application/x-www-form-urlencoded";
hr.ContentLength = buf.Length;
hr.Method = "POST";
System.IO.Stream RequestStream = hr.GetRequestStream();
RequestStream.Write(buf, 0, buf.Length);
RequestStream.Close();
System.Net.WebResponse response = hr.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
string ReturnVal = reader.ReadToEnd();
reader.Close();
response.Close();
return ReturnVal;
}
public static byte[] StreamToBytes(Stream stream)
{
List<byte> bytes = new List<byte>();
int temp = stream.ReadByte();
while (temp != -1)
{
bytes.Add((byte)temp);
temp = stream.ReadByte();
}
return bytes.ToArray();
}
}
}
其中GetHtml方法为http get请求
PostData 为post请求 参数格式如下 par=data&par=data