如何在 Delphi 中使用XMLHTTPRequest获取图像二进制数据

7cjasjjr  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(141)

我需要在 Delphi 中使用XMLHttpRequest访问二进制图像数据。我使用以下代码,但它不工作,有人能告诉我这段代码有什么问题吗?

//I am using this function to get Image Binary data into Memory Stream.
procedure SendGETRequest(p_Url: string; p_resStream: TMemoryStream);
begin  
  FXmlHttpReq.open(METHOD_GET, p_Url, false, FUsername, FPassword);
  FXmlHttpReq.setRequestHeader(HTTP_AUTHENTICATION, HTTP_BASIC + EncodeBase64(
    FUsername + ':'+FPassword));
  FXmlHttpReq.setRequestHeader(HTTP_CACHE_CONTROL, HTTP_NO_CACHE);
  //FXmlHttpReq.setRequestHeader('Content-type','application/octet-stream');
  FXmlHttpReq.send('');

  if not VarIsEmpty(FXmlHttpReq.responseBody) then
  begin
   p_resStream:= OleVariantToMemoryStream(FXmlHttpReq.responseStream);
  end;//if...
end;

function OleVariantToMemoryStream(OV: OleVariant): TMemoryStream;
var
  Data: PByteArray;
  Size: integer;
begin
  Result := TMemoryStream.Create;
  try
    Size := VarArrayHighBound (OV, 1) - VarArrayLowBound(OV, 1) + 1;
    Data := VarArrayLock(OV);
    try
      Result.Position := 0;
      Result.WriteBuffer(Data^, Size);
   finally
     VarArrayUnlock(OV);
   end;
  except
    Result.Free;
    Result := nil;
  end;
end;

字符串

rqenqsqc

rqenqsqc1#

responseStreamIStream。您需要使用TOleStreamAxCtrls)转换它:

uses AxCtrls, ComObj, ActiveX;

procedure TForm1.Button1Click(Sender: TObject);
var
  oXMLHTTP: OleVariant;
  MemoryStream: TMemoryStream;
  Stream: IStream;
  OleStream: TOleStream;
begin
  oXMLHTTP := CreateOleObject('MSXML2.XMLHTTP.3.0');
  oXMLHTTP.open('GET', 'https://www.google.com/images/srpr/logo11w.png', False);
  oXMLHTTP.send(EmptyParam);
  Stream := IUnknown(oXMLHTTP.ResponseStream) as IStream;
  OleStream := TOleStream.Create(Stream);
  try
    OleStream.Position := 0;
    MemoryStream := TMemoryStream.Create;
    try
      MemoryStream.CopyFrom(OleStream, OleStream.Size);
      MemoryStream.SaveToFile('logo11w.png');
    finally
      MemoryStream.Free;
    end;
  finally
    OleStream.Free;
  end;
end;

字符串

snz8szmq

snz8szmq2#

If HttpReq.Status = 200 Then begin
   try
     //https://stackoverflow.com/questions/4938601/getting-an-istream-from-an-olevariant
     strm:= getmemStreamfromIStream2(HttpReq.responsestream);
     //getmemStreamfromIStream2file(hrstream, apath);
     writeln('responsestream size: '+itoa(strm.size)); 
     strm.savetoFile(apath)
     openFile(apath);  
   except
     writeln('EHTTPex: '+ExceptiontoString(exceptiontype, exceptionparam));
   finally
     strm.free;
     httpreq:= unassigned; 
   end;  
end;

字符串
//来自maXbox 5

相关问题