我正在用C#编写安卓应用程序。
我解析来自JSON的信息,然后在字段中显示它。
我使用以下代码:
string url2 = "http://papajohn.pp.ua/?mkapi=getProductsByCat&cat_id=74";
JsonValue json = await FetchAsync(url2);
private async Task<JsonValue> FetchAsync(string url)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
//dynamic data = JObject.Parse(jsonDoc[15].ToString);
Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
// Return the JSON document:
return jsonDoc;
}
}
}但我有一个问题。当我打开活动,它冻结2-3秒,然后所有的信息显示在字段。
我能顺利下载这些数据吗?第一场,第二场,等等。
如果可以的话,怎么做?
发布于 2016-04-14 23:23:29
我建议在C#中实现异步/等待的正确使用,并切换到HttpClient,这也实现了异步/等待的正确使用。下面是一个代码示例,它将在UI线程之外检索您的Json:
var url2 = "http://papajohn.pp.ua/?mkapi=getProductsByCat&cat_id=74";
var jsonValue = await FetchAsync(url2);
private async Task<JsonValue> FetchAsync(string url)
{
System.IO.Stream jsonStream;
JsonValue jsonDoc;
using(var httpClient = new HttpClient())
{
jsonStream = await httpClient.GetStreamAsync(url);
jsonDoc = JsonObject.Load(jsonStream);
}
return jsonDoc;
}如果要在Android项目中编写代码,则需要添加System.Net.Http DLL作为参考。如果使用aPCL编写代码,则需要安装Microsoft Http客户端库Nuget包。为了提高性能,我建议使用ModernHttpClient,它也可以从Nuget安装。
发布于 2016-04-15 06:39:29
您在HttpWebRequest中的异步等待使用是正确的。从活动中错误调用此方法可能会导致UI冻结。我将解释如何调用下面。
我还建议使用ModernHttpClient库来加速API调用。
public static async Task<ServiceReturnModel> HttpGetForJson (string url)
{
using (var client = new HttpClient(new NativeMessageHandler()))
{
try
{
using (var response = await client.GetAsync(new Uri (url)))
{
using (var responseContent = response.Content)
{
var responseString= await responseContent.ReadAsStringAsync();
var result =JsonConvert.DeserializeObject<ServiceReturnModel>(responseString);
}
}
}
catch(Exception ex)
{
// Include error info here
}
return result;
}
}您将需要包括ModernHttpClient和JSON.NET (Newtonsoft.Json)
从活动中调用此方法而不阻塞UI
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
// After doing initial Setups
LoadData();
}
// This method downloads Json asynchronously without blocking UI and without showing a Pre-loader.
async Task LoadData()
{
var newRequestsResponse =await ServiceLayer.HttpGetForJson (newRequestsUrl);
// Use the data here or show proper error message
}
// This method downloads Json asynchronously without blocking UI and shows a Pre-loader while downloading.
async Task LoadData()
{
ProgressDialog progress = new ProgressDialog (this,Resource.Style.progress_bar_style);
progress.Indeterminate = true;
progress.SetProgressStyle (ProgressDialogStyle.Spinner);
progress.SetCancelable (false);
progress.Show ();
var newRequestsResponse =await ServiceLayer.HttpGetForJson (newRequestsUrl);
progress.Dismiss ();
// Use the data here or show proper error message
}材料型装载机样式。将包含在参考资料/值/Style.xml中
<style name="progress_bar_style">
<item name="android:windowFrame">@null</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowTitleStyle">@null</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:background">@android:color/transparent</item>
https://stackoverflow.com/questions/36632981
复制相似问题