使用indy解析http协议的multipart上传数据
MMS彩信的数据附在Soap包后面,在正常解析soap的xml文件外,还需要对使用multipart/related编码上传的数据做解析处理,在indy中提供了解码类。
处理解码时,需要TIdMessageDecoderMIME负责实际的解码, TIdMIMEBoundary从头信息中做边界信息查找。
解码函数
-
procedure DecodeFormData(const sHeader: String; ASourceStream:TStream; sSavePath: String);
-
var
-
bEnd : Boolean;
-
sTmp: String;
-
Decoder: TIdMessageDecoderMIME;
-
ds: TStream;
-
begin
-
bEnd := False;
-
Decoder := TIdMessageDecoderMIME.Create(nil);
-
-
try
-
// 设置附件的边界
-
Decoder.MIMEBoundary := TIdMIMEBoundary.FindBoundary(sHeader);
-
Decoder.SourceStream := ASourceStream;
-
Decoder.ReadLn;
-
-
repeat
-
Decoder.ReadHeader; // 读入分块的Header信息
-
case Decoder.PartType of
-
mcptUnknown:
-
raise Exception.Create('Unknown form data detected');
-
mcptText:
-
begin
-
sTmp := Decoder.Headers.Values['Content-Type']; // 获取ContentType
-
ds := TMemoryStream.Create;
-
try
-
Decoder := Decoder.ReadBody(ds,bEnd);
-
// 如果取的数据仍然是由多块组成,则进行递归处理
-
if AnsiSameText(Fetch(Tmp, ';'),'multipart/mixed') then
-
DecodeFormData(sTmp, ds, sSavePath)
-
else
-
// 根据需要使用Dest的数据
-
finally
-
FreeAndNil(ds);
-
end;//try
-
end; // mcptText
-
-
mcptAttachment:
-
begin
-
// 处理附件的文件名
-
sTmp := ExtractFileName(Decoder.FileName);
-
if sTmp <> '' then
-
sTmp := sSavePath + sTmp
-
else
-
sTmp := MakeTempFilename(sSavePath);
-
-
ds := TFileStream.Create(sTmp, fmCreate);
-
try
-
Decoder := Decoder.ReadBody(ds,bEnd);
-
finally
-
FreeAndNil(ds);
-
end;//try
-
end; // mcptAttachment
-
end; // case
-
until (Decoder = nil) or bEnd;
-
finally
-
FreeAndNil(Decoder);
-
end;//try
-
end;
使用OnCreatePostStream 创建用来接受HttpPost数据的Stream
-
CreatePostStream(ASender: TIdPeerThread; var VPostStream: TStream);
-
begin
-
VPostStream := TMemoryStream.Create;
-
end;
最后在OnCommandGet中做解析处理
-
OnCommandGet(ASender: TIdPeerThread; ARequestInfo: TIdHttpRequestInfo; AResponseInfo: TIdHttpResponseInfo);
-
var
-
sContentType : String
-
begin
-
sContentType := ARequestInfo.ContentType;
-
-
if AnsiSameText(Fetch(S, ';'), 'multipart') then begin
-
DecodeFormData(sContentType, ARequestInfo.PostStream, 'c:temp');
-
end else
-
// 根据需要对请求数据做处理…
-
end;
Popularity: 6% [?]