//1.使用Dictionary字典提交数据,这样比较清晰。(针对对象)
var jsonTextReplace = jsonText.Replace("[", " ").Replace("]", "");
var jo = JObject.Parse(jsonTextReplace);
string UserCard = jo["UserCard"].ToString();
string Residential = jo["Residential"].ToString();
string FloorId = jo["FloorId"].ToString();
string UnitId = jo["UnitId"].ToString();
string LayerId = jo["LayerId"].ToString();
string RoomID = jo["RoomID"].ToString();
string Address = jo["Address"].ToString();
string UserName = jo["UserName"].ToString();
string ConstructionArea = jo["ConstructionArea"].ToString();
string DeviceNo = item.DeviceNo;
IDictionary<string, string> para = new Dictionary<string, string>();
para.Add("CommunityAddress", Address);
para.Add("CommunityHotArea", "1");
para.Add("CommunityName", Residential);
para.Add("BuildingNo", FloorId);
para.Add("UnitNo", UnitId);
para.Add("Floor", LayerId);
para.Add("HouseNo", RoomID);
para.Add("UserCode", UserCard);
string info = JsonConvert.SerializeObject(para).ToString();
public static string HttpPost(string url, string paramData, Dictionary<string, string> headerDic = null)
{
string result = string.Empty;
try
{
HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
wbRequest.Method = "POST";
//wbRequest.ContentType = "application/x-www-form-urlencoded";
wbRequest.ContentType = "application/json";
wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
if (headerDic != null && headerDic.Count > 0)
{
foreach (var item in headerDic)
{
wbRequest.Headers.Add(item.Key, item.Value);
}
}
using (Stream requestStream = wbRequest.GetRequestStream())
{
using (StreamWriter swrite = new StreamWriter(requestStream))
{
swrite.Write(paramData);
}
}
HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
using (Stream responseStream = wbResponse.GetResponseStream())
{
using (StreamReader sread = new StreamReader(responseStream))
{
result = sread.ReadToEnd();
}
}
}
catch (Exception ex)
{
}
return result;
}
//2.参数少的情况下,直接拼接参数字符串
private string PostWebRequest(string postUrl, string paramData)
{
string responseContent = string.Empty;
try
{
byte[] byteArray = Encoding.UTF8.GetBytes(paramData); //转化
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.ContentLength = byteArray.Length;
using (Stream reqStream = webReq.GetRequestStream())
{
reqStream.Write(byteArray, 0, byteArray.Length);
}
using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default))
{
responseContent = sr.ReadToEnd().ToString();
}
}
}
catch (Exception e)
{
return "204";
}
return responseContent;
}