-->

上传文件使用HttpSendRequest中的C ++(uploading files using

2019-09-26 15:13发布

我试图通过POST请求(C ++和WINAPI),步骤,将文件发送到HTTP服务器:

// Read file into "buff" and file size into "buffSize" 
        ....
    ....
    ....

    HINTERNET internetRoot;
    HINTERNET httpSession;
    HINTERNET httpRequest;

    internetRoot = InternetOpen(agent_info, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, NULL);

    //Connecting to the http server
    httpSession = InternetConnect(internetRoot, IP,PORT_NUMBER, NULL, NULL, INTERNET_SERVICE_HTTP, NULL, NULL);

    //Creating a new HTTP POST request to the default resource on the server
    httpRequest = HttpOpenRequest(httpSession, TEXT("POST"), TEXT("/Post.aspx"), NULL, NULL, NULL, INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE, NULL);

    //Send POST request
    HttpSendRequest(httpRequest, NULL, NULL, buff, buffSize);

    //Closing handles...

在服务器我recieving使用此代码(asp.net)文件

Stream httpStream;
        try
        {
            httpStream = request.RequestContext.HttpContext.Request.InputStream;
        }
        catch (HttpException)
        {
            return;
        }

            byte[] tmp = new byte[httpStream.Length];
            int bytesRead = httpStream.Read(tmp, 0, 1024 * 1024);
            int totalBytesRead = bytesRead;
            while (bytesRead > 0)
            {
                bytesRead = httpStream.Read(tmp, totalBytesRead, 1024 * 1024);
                totalBytesRead += bytesRead;
            }
            httpStream.Close();
            httpStream.Dispose();

           //Save "tmp" to file...

我可以将本地服务器(视觉工作室ASP服务器)上发送大文件,但我不能超过1 MB的文件发送到互联网服务器。 (HttpOpenRequest中失败)是否有更好的方式来上传文件?

Answer 1:

警告:我的Wininet是很生疏的这些日子。

我不知道你是否应该被设置“的Content-Length”头自己。 你的代码似乎要认为)你是一个HTTP / 1.0请求或b)该HttpSendRequest会添加标题为你(我不认为它)。

没有服务器无论哪种方式被告知传入的请求有多大IIS的默认配置会拒绝它,如果它不能确定请求大小本身快。

我的猜测是,如果你使用lpszHeadersdwHeadersLength的参数HttpSendRequest功能,包括适当的“内容长度”报头的问题将得到解决。



Answer 2:

你收到了什么错误? 我的意思是什么呢GetLastError()返回? 如果您发送的文件800KB然后它的作品好不好? 我真的不看看,因为HttpOpenRequest中不知道数据的大小。

也许是超时? 但是,这将意味着,实际上HttpSendRequest中的失败。 它可能会缓冲所有数据,但由于规模巨大,则需要更多的时间比超时允许。

使用下面的代码来查询当前超时(毫秒):

InternetQueryOption(h, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwReceiveTimeOut, sizeof(dwReceiveTimeOut));
InternetQueryOption(h, INTERNET_OPTION_SEND_TIMEOUT, &dwSendTimeOut, sizeof(dwSendTimeOut));

并按照设定新的:

InternetSetOption(h, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwNewReceiveTimeOut, sizeof(dwNewReceiveTimeOut));
InternetSetOption(h, INTERNET_OPTION_SEND_TIMEOUT, &dwNewSendTimeOut, sizeof(dwNewSendTimeOut));


文章来源: uploading files using httpSendRequest c++