C#windowForm 从php函数返回的Url获取到json并解析,下载文件
2014-11-03 15:45
633 查看
WebClient client = new WebClient(); string phpURL = "http://222.31.76.240:8080/?r=databaseInterface/GetdetailsBySongAndArtistName&songName=That Will Be The Day&artistName=%E9%99%88%E5%A5%95"; //从php函数返回的url获取数据 byte[] data = client.DownloadData(phpURL); string str = System.Text.Encoding.ASCII.GetString(data); //多条项的时候,解析如下: int pre = str.IndexOf("["); string M = "\"songLocation\":\""; string N = "\",\"lyricsLocation"; int s = 0; while ((s = str.IndexOf("{", pre)) >= 0) { int m = str.IndexOf(M, s) + M.Length; int n = str.IndexOf(N, s); string temp = str.Substring(m, n - m); string url = temp.Replace("\\", ""); string regix = url.Substring(url.LastIndexOf(".")); //后缀名,eg:.mp3 string fileName = "安静"; string filePath = fileName + regix; try { //文件重名的操作 int count = 0;//目前已有的文件名的数 while (File.Exists(filePath)) { count++; filePath = fileName + "(" + count + ")" + regix; } //下载文件 WebClient myWebClient = new WebClient(); myWebClient.DownloadFile(url, filePath); } catch (Exception msg) { MessageBox.Show(msg.Message); } pre = n; }
文件下载参见:http://stackoverflow.com/questions/307688/how-to-download-a-file-from-a-url-in-c
注:WebClient下载,实验了10次,每次数据都能接受全。若是采用下面的方法,则8次有4次不能收齐数据
try
{
WebRequest request;
WebResponse response;
request = WebRequest.Create(url);//图片src内容
const long ChunkSize = 102400;
byte[] buffer = new byte[ChunkSize];
response = request.GetResponse();
//文件流获取mp3文件,不知道什么原因有事下载不全
Stream reader = response.GetResponseStream();
int count = 0;//目前已有的文件名
while (File.Exists(filePath))
{
count++;
filePath = fileName+"("+count+")"+regix;
}
FileStream writer = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
int lengthRead;
while ((lengthRead = reader.Read(buffer, 0, Convert.ToInt32(ChunkSize))) > 0)
{
writer.Write(buffer, 0, lengthRead);
writer.Flush();
}
//释放资源
writer.Close();
writer.Dispose();
reader.Close();
reader.Dispose();
response.Close();
}
catch (Exception msg)
{
MessageBox.Show(msg.Message);
}
相关文章推荐
- c# 通过访问URL,获取并解析远程服务端返回的复杂Json数据
- Jquery form.js文件上传返回JSON数据,在IE下提示下载文件的解决办法,并对返回数据进行正确的解析
- struts2 + ajax(由前台的form提交数据到后台,再根据form所调用返回获取的后台json格式的数据返回到前端,然后前端用jquery对json数据进行解析)==》》涉及文件上传的部分
- 从服务器用xutils获取json,并用gson解析,包括用xutils下载文件
- ajax批量下载文件,动态构建一个Form 并且提交获取返回的文件流
- IE无法解析返回的JSON格式并提示下载文件
- C#根据指定url下载文件并读取.csv数据转为json格式
- struts2 + ajax(由前台的form提交数据到后台,再根据form所调用返回获取的后台json格式的数据返回到前端,然后前端用jquery对json数据进行解析)==》》涉及非文件上传的部分
- URL跨项目调用方法,获取返回的json值,并解析
- form+iframe上传文件返回json在IE下提示下载的问题(源于ueditor的错误)(从ITEYE搬家过来的)
- jquery的ajaxForm在IE上传文件后返回json显示"文件下载"问题
- 通过JSON文件获取图片URL,下载并显示在布局中
- IE无法解析返回的JSON格式并提示下载文件
- android:通过url向网络端获取json格式数据并解析显示
- C#实现用Newtonsoft.Json 4.5.11解析人人网院校信息并获取院系信息
- Ext.form.Panel 上传文件,不依赖服务端的Json返回
- C# 获取天气 JSON解析
- c#解析json文件的方法
- Android中数据文件解析(Json解析【从服务器端获取数据并且解析,显示在客户端上面】)
- Android中数据文件解析(Json解析【从服务器端获取数据并且解析,显示在客户端上面】)