我想将文件http://img1.ak.crunchyroll.com/i/croll_manga/e/257692e8c297b8907e2607964454b941_1438752352_main下载到字符串。
在C ++中我写了函数
string opener(string url)
{
CURL *curl;
CURLcode res;
std::string readBuffer;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
return readBuffer;
}
这项工作正常。
在C#中我写了这个课程
namespace Crmrip
{
class opener
{
public static string open(string url)
{
using (WebClient page = new WebClient())
{
try
{
page.Encoding = Encoding.UTF8;
page.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0";
string result = page.DownloadString(url);
return result;
}
catch (WebException er)
{
MessageBox.Show(er.ToString());
return null;
}
}
}
}
}
这个班级工作不正常。下载的文件太大了。 用C ++下载的文件有487 778字节,没问题。 用C#下载的文件有879 910,太大了。
为什么用C#下载的文件太大了?
答案 0 :(得分:0)
使用DownloadData
将响应作为字节数组获取。执行XOR并将结果写入文件
所以稍微改变你的代码:
using (WebClient page = new WebClient())
{
try
{
byte[] result = page.DownloadData(url);
for(int i=0;i<result.Length;i++)
{
result[i] ^= 0x42;
}
File.WriteAllBytes(filename, result);
}
catch (WebException er)
{
MessageBox.Show(er.ToString());
}
}
答案 1 :(得分:0)
似乎工作:
void Main()
{
string url = "http://img1.ak.crunchyroll.com/i/croll_manga/e/257692e8c297b8907e2607964454b941_1438752352_main";
Console.WriteLine(open(url));
}
public static async Task<string> open(string url)
{
using (HttpClient page = new HttpClient())
{
try
{
//page.Encoding = Encoding.UTF8;
//page.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0";
page.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0");
return await page.GetStringAsync(url);
}
catch (Exception er)
{
//MessageBox.Show(er.ToString());
return null;
}
}
}
我不确定编码是否会成为问题 - 这里是reference