最近做项目开发需要上传用户行为数据,采用C#来上传数据
使用了HttpWebRequest 来实现
传输方式采用的是POST的方式
内容格式采用application/json
具体实现的代码如下:
public static string HttpPostRaw(string url, string data)
{
string value = "";
try
{
HttpWebRequest reqest = (HttpWebRequest)WebRequest.Create(url);
reqest.Method = "POST";
reqest.ContentType = "application/json";
Stream stream = reqest.GetRequestStream();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(data);
stream.Write(bs, 0, bs.Length);
stream.Flush();
stream.Close();
HttpWebResponse response = (HttpWebResponse)reqest.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
value = sr.ReadToEnd();
response.Close();
return value;
}
catch (Exception ex)
{
error = ex.ToString();
return "";
}
}