2012-04-12 80 views
2

我收到遠程服務器在嘗試運行我的代碼時返回錯誤:(400)錯誤的請求錯誤。任何幫助,將不勝感激。謝謝。如何解決400錯誤請求錯誤?

// Open request and set post data 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("myurl.com/restservice/Login"); 
    request.Method = "POST"; 
    request.ContentType = "application/json; charset:utf-8"; 
    string postData = "{ \"username\": \"testname\" },{ \"password\": \"testpass\" }"; 

    // Write postData to request url 
    using (Stream s = request.GetRequestStream()) 
    { 
     using (StreamWriter sw = new StreamWriter(s)) 
      sw.Write(postData); 
    } 

    // Get response and read it 
    using (Stream s = request.GetResponse().GetResponseStream()) // error happens here 
    { 
     using (StreamReader sr = new StreamReader(s)) 
     { 
      var jsonData = sr.ReadToEnd(); 
     } 
    } 

JSON編輯

更改爲:

{ \"username\": \"jeff\", \"password\": \"welcome\" } 

但仍然沒有工作。

編輯

這是我發現的工作原理:

 // Open request and set post data 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("myurl.com/restservice/Login"); 
    request.Method = "POST"; 
    request.ContentType = "application/json"; 
    string postData = "{ \"username\": \"testname\", \"password\": \"testpass\" }"; 

    // Set postData to byte type and set content length 
    byte[] postBytes = System.Text.UTF8Encoding.UTF8.GetBytes(postData); 
    request.ContentLength = postBytes.Length; 

    // Write postBytes to request stream 
    Stream s = request.GetRequestStream(); 
    s.Write(postBytes, 0, postBytes.Length); 
    s.Close(); 

    // Get the reponse 
    WebResponse response = request.GetResponse(); 

    // Status for debugging 
    string ResponseStatus = (((HttpWebResponse)response).StatusDescription); 

    // Get the content from server and read it from the stream 
    s = response.GetResponseStream(); 
    StreamReader reader = new StreamReader(s); 
    string responseFromServer = reader.ReadToEnd(); 

    // Clean up and close 
    reader.Close(); 
    s.Close(); 
    response.Close(); 
+0

爲什麼你在使用Streams?請改用['WebClient'](http://msdn.microsoft.com/zh-cn/library/system.net.webclient.aspx)! – qJake 2012-04-12 20:40:31

+0

WebClient是一個好主意。但是請注意,400請求通常表示服務器不理解您的請求。壞的負載是可能的罪魁禍首,尤其是因爲你似乎有不正確的JSON。 – yamen 2012-04-12 20:43:45

回答

4

可以嘗試string postData = "[{ \"username\": \"testname\" },{ \"password\": \"testpass\" }]";

您發送2個對象

編輯所組成的數組方式:也許你真的想發送什麼只是有2個屬性的對象,那麼這將是string postData = "{ \"username\": \"testname\", \"password\": \"testpass\" }"

+3

如果數據無效,許多REST服務會返回HTTP 400,例如Viamenete和Palletways – rastating 2012-04-12 20:42:32

+0

問題可能是** postData **嗎?它看起來像是從字面上發送\斜槓。 – 2012-04-12 20:51:57

+0

我不認爲這會是一個問題,他們只是逃避角色..你在哪裏看到這些斜槓被髮送? – jorgehmv 2012-04-12 20:58:31

0

看起來好像它可能從您發佈,因爲它是無效的,請參閱下面你要發送什麼,但在一個有效的形式JSON現身:

{ 
    "username": "testname", 
    "password": "testpass" 
} 
+0

正如我在其他評論中所說的,如果數據無效,許多REST服務會返回HTTP 400,例如Viamenete和Palletways。我今天剛剛開始使用基於HTTP的Web服務來完成同樣的事情。 – rastating 2012-04-12 20:43:26