C++中利用WebService下载文件
C#寫的WebService讀取文件到byte[]和讀取文件內容到string,代碼如下:
[WebMethod]
public byte[] dowloadFile()
{
??? FileStreamreader = null;
??? stringfilePath = "C:/Inetpub/wwwroot/ws/wrar38b2sc.exe";
???try
??? {
???????reader = new FileStream(filePath, FileMode.Open,FileAccess.Read);
???????byte[] bytes = new byte[reader.Length];
???????reader.Read(bytes, 0, Convert.ToInt32(reader.Length));
???????reader.Close();
???????return bytes;
??? }
??? catch(Exception ex)
??? {
???????throw ex;
??? }
???finally
??? {
???????reader.Close();
??? }
}
?
[WebMethod]
public string ReadFileToString()
{
???StreamReader sr =File.OpenText("C:/Inetpub/wwwroot/ws/test.txt");
???StringBuilder sb = new StringBuilder();
??? while(!sr.EndOfStream)
??? {
???????sb.Append(sr.ReadLine());
??? }
???sr.Close();
??? returnsb.ToString();
}
?
C++中調用WebService下載文件
//在工程中添加web引用,添加成功后,既可以編寫代碼如下
#include "stdafx.h"
#include "WebService.h"
#include <comdef.h>
using namespace Service;
using namespace std;
?
//調用返回值是字符串類型的WebService方法
void ReadFileToString()
{
?CoInitialize(NULL);
?HRESULT hr =S_OK;
?BSTR hiResult;
?CService*myService = new CService;?//代理對象,這個對象能從類視圖中看到
?//myService->SetUrl(L"http://192.168.1.158/ws/Service.asmx");
?hr =myService->ReadFileToString(&hiResult);
?_bstr_t bb =hiResult;
?char* c = bb;
?if(FAILED(hr))
?{
??printf("ReadFileToString調用失敗\n");
?}
?else
?{
??printf("ReadFileToString調用結果:%s\n",c);
?}
?SysFreeString(hiResult);
?delete myService;
?CoUninitialize();
}
?
//調用返回值是byte[]類型的WebService方法,并轉成對應文件
void dowloadFile()
{
?//當下來的文件名稱,因為WebService方法只返回了文件內容,沒有文件名稱
?//
?char *fileName = "wrar38b2sc.exe";
?CoInitialize(NULL);
?HRESULT hr =S_OK;
?ATLSOAP_BLOB hiResult;
?CService*myService = new CService;?//代理對象,這個對象能從類視圖中看到
?//發布之后的WebSerivce地址,可以寫,也可以不寫,我在不寫的情況下執行成功
?//myService->SetUrl(L"http://192.168.1.158/ws/Service.asmx");
?hr =myService->dowloadFile(&hiResult);
?unsigned char* c= hiResult.data;
?if(FAILED(hr))
?{
??printf("dowloadFile調用失敗\n");
?}
?else
?{
??printf("dowloadFile調用結果:%s\n",c);
?}
?FILE*fp;???
?fp = fopen(fileName, (const char*)("wb"));
?fwrite(hiResult.data, hiResult.size, 1,fp);
?free(hiResult.data);???
?fclose(fp);
?delete myService;
?CoUninitialize();
?//執行文件
? WinExec(fileName, SW_SHOW);
}
總結
以上是生活随笔為你收集整理的C++中利用WebService下载文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++利用gSoap调用WebServi
- 下一篇: VC获取其他进程ListCtrl内容