0
我正在將Windows應用程序上的WebAppication重寫爲本機應用程序。AJAX與HTTPRequest
我陷入了一點麻煩,無法發佈數據。
這裏是WebApplication的代碼 - 它的工作原理:
$.ajax({
url: 'https://blabla.blabla.com/mobile-api/v1/security',
contentType: 'application/json',
// data: JSON.stringify ({"jsonrpc": "2.0", "method": "login", "params":["TestLogin", "SuperPass"], "id": 1}),
data: JSON.stringify({"jsonrpc": "2.0", "method": "login", "params":[username, password], "id": 1}),
type:"POST",
success: function(data){
callback.onSuccess(data);
},
error: function(xhr){
callback.onError(xhr.status);
}
});
這裏是我的C#代碼:
private void PostLoginData()
{
HttpWebRequest request = HttpWebRequest.CreateHttp("https://blabla.blabla.com/mobile-api/v1/security");
request.Method="POST";
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback),request);
}
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
// End the stream request operation
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
// Create the post data
string postData = "{\"jsonrpc\": \"2.0\", \"method\": \"login\", \"params\":{\"username\":" + "\"TestLogin\"" + ", \"password\":" + "\"SuperPass\"" + "}, \"id\": 1}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}
void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result = httpWebStreamReader.ReadToEnd();
//For debug: show results
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(result);
});
}
}
響應返回我:
無效的方法參數。
如果我嘗試後登錄名和密碼沒有 「」,像這樣:
string postData = "{\"jsonrpc\": \"2.0\", \"method\": \"login\", \"params\":{\"username\":" + "TestLogin" + ", \"password\":" + "SuperPass" + "}, \"id\": 1}";
的迴應是:
解析錯誤
登錄名和密碼是100%正確...問題我認爲是在發佈數據,因爲WebApplications的請求工作