1. 程式人生 > >post數據時報錯:遠程服務器返回錯誤: (400) 錯誤的請求。

post數據時報錯:遠程服務器返回錯誤: (400) 錯誤的請求。

lose tle content protected write pan ebr read 遠程服務

網上查了多種方法,有不少說法,報400說是傳的數據格式不對,最後的結論確實是數據格式不對。

Content_Type為:application/json,配的數據格式有些麻煩,特別數多層,單層還好。
例如,我本傳的數據是這個的json:

{
  "key1": {
    "key11": "value11",
    "key12": "value12"
  },
  "key2": "value2"
}

這時候,postData應該為:{"client":"{\"machineId\":\"1040\",\"value\":\"1\"}","userId":"5","temp":"91D3EB4181237881A227DF29B304738D"}

c#裏賦值寫法為:

string _postData = "{\"client\":\"{\\\"machineId\\\":\\\"1040\\\",\\\"value\\\":\\\"1\\\"}\",\"userId\":\"5\",\"temp\":\"91D3EB4181237881A227DF29B304738D\"}";

post的方法:

  protected string PostUrl(string url, string postData)
    {
        try
        {
            HttpWebRequest webrequest 
= (HttpWebRequest)HttpWebRequest.Create(url); webrequest.Method = "post"; webrequest.ContentType = "application/json;charset=utf-8"; byte[] postdatabyte = Encoding.UTF8.GetBytes(postData); webrequest.ContentLength = postdatabyte.Length; Stream stream; stream
= webrequest.GetRequestStream(); stream.Write(postdatabyte, 0, postdatabyte.Length); stream.Close(); using (var httpWebResponse = webrequest.GetResponse()) using (StreamReader responseStream = new StreamReader(httpWebResponse.GetResponseStream())) { String ret = responseStream.ReadToEnd(); string result = ret.ToString(); return result; } } catch (Exception ex) { HttpContext.Current.Response.Write(ex); return ""; } }

如果posData的格式寫錯,運行後報錯(using (var httpWebResponse = webrequest.GetResponse())):System.Net.WebException: 遠程服務器返回錯誤: (400) 錯誤的請求。 在 System.Net.HttpWebRequest.GetResponse() 。

post數據時報錯:遠程服務器返回錯誤: (400) 錯誤的請求。