[英]Retrieve JSON string from URL in Windows Phone 8
我正在嘗試從Windows Phone 8應用程序中的Url獲取一個Json字符串(該頁面需要身份驗證,我認為這是我的代碼失敗的地方),我正在使用以下代碼:
public WebClient client = new WebClient();
public string result;
public void DoStuff()
{
string username = "username";
string password = "password";
string url = "myurl";
client.Credentials = new NetworkCredential(username, password);
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
client.DownloadStringAsync(new Uri(url));
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
result = e.Result;
}
但是,運行該應用程序時,在e.result上出現了System.Reflection.TargetInvocationException
進入InnerException我看到了:
[System.Net.WebException] {System.Net.WebException:WebClient請求期間發生異常。 ---> System.Net.ProtocolViolationException:使用此方法的請求不能具有請求主體。 在System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod,Object state)在System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)在System.Net.WebClient.GetWebResponse(WebRequest request,IAsyncResult result) .WebClient.DownloadBitsResponseCallback(IAsyncResult result)---內部異常堆棧跟蹤的結尾---} System.Net.WebException
我嘗試使用HttpClient,但遇到了同樣的問題。 我想知道是否有人知道如何解決這個問題。
謝謝!
更新:我嘗試使用IE導航到手機上的頁面,然后IE Mobile說:“地址不受支持,IE Mobile不支持這種類型的地址,因此無法顯示此頁面”。 這就是為什么應用程序也崩潰的原因?
GET方法(具有/不具有憑據)
private string username = "user";
private string password = "passkey";
private string myUrl = "http://some_url.com/id?=20";
private WebClient client = new WebClient();
private void retrieveJson()
{
client.Credentials = new NetworkCredential(username, password);
client.Encoding = Encoding.UTF8;
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
client.DownloadStringAsync(new Uri(myUrl), UriKind.Relative);
}
//WebClient String (json content) Download
private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
// You will get you Json Data here..
var myJSONData = e.Result;
JObject JsonData = JObject.Parse(myJSONData);
//Do something with json
//Ex: JsonData["Array1"][5]
}
POST方法(具有/不具有憑據)
private string username = "user";
private string password = "passkey";
private string myUrl = "http://some_url.com/id?=20";
private WebClient client = new WebClient();
private string parameters = "{\"I_NAME\":\"0000"\"}"; //Example
private void postMethod()
{
client.Credentials = new NetworkCredential(username, password);
client.Encoding = Encoding.UTF8;
client.Headers["Content-Length"] = parameters.Length.ToString();
client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompleted);
client.UploadStringAsync(new Uri(myUrl), "POST", parameters);
}
private void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Error == null)
{
var myJSONData = e.Result;
JObject JsonData = JObject.Parse(myJSONData);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.