您的位置:首页 > 编程语言 > PHP开发

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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐