使用Delphi获取Microsoft翻译时获得400响应
我已经在Azure上注册了我的应用程序,收到了一个秘密,并成功地使用TIdHTTP和我的Delphi 2010获得了一个访问令牌:使用Delphi获取Microsoft翻译时获得400响应,delphi,azure,delphi-2010,bad-request,microsoft-translator,Delphi,Azure,Delphi 2010,Bad Request,Microsoft Translator,我已经在Azure上注册了我的应用程序,收到了一个秘密,并成功地使用TIdHTTP和我的Delphi 2010获得了一个访问令牌: paramsList := TStringList.Create; paramsList.Add('grant_type=client_credentials'); paramsList.Add('client_id=<ClientID>'); paramsList.Add('client_secret=<ClientSecret>'); p
paramsList := TStringList.Create;
paramsList.Add('grant_type=client_credentials');
paramsList.Add('client_id=<ClientID>');
paramsList.Add('client_secret=<ClientSecret>');
paramsList.Add('scope=http://api.microsofttranslator.com');
try
Result := idHTTP.Post(uri, lParamList);
finally
FreeAndNill(idHTTP);
FreeAndNill(paramsList);
end;
我也无法使用post获得响应:
paramList := TStiringList.Create;
paramList.Add('Authorization= Bearer ' + Token);
try
idHTTP.Post(uri, paramList);
finally
...
还是一样的回答-400,有什么想法吗?首先,事实是:当在Microsoft Translator请求访问令牌时,您使用Post,当使用访问令牌访问API时,您使用Get(谢谢@RemyLebeau)。现在是代码。上面用于接收访问令牌的代码有效。因此,获取翻译的代码也是直截了当的:
lHTTP.Request.CustomHeaders.FoldLines := false; // avoid split by white space
lHTTP.Request.CustomHeaders.AddValue('Authorization', 'Bearer ' + AuthKey);
myStream = TStringStream.Create;
try
lHTTP.Get(uri, stream);
stream.Position := 0;
Result := stream.ReadString(stream.size);
finally
FreeAndNil(lHTTP);
FreeAndNil(stream);
end;
下面是一个工作示例
退房://
单位MSTranslationv2;
界面
使用
类、sysutil、,
IdBaseComponent、IdComponent、IdTCPConnection、IdTCPClient、,
IdHTTP、IDoHandler、IDoHandlerSocket、IDoHandlerStack、IdSSL、,
idssl;
类型
TMSTranslator=类(t组件)
IdHTTP:TIdHTTP;
idsslioohandlersocketopenssl:tidslioohandlersocketopenssl;
私有的
f母语:字符串;
fClientID:字符串;
fClientSecret:字符串;
语言:字符串;
AuthKey:string;
{私有声明}
函数GetAuthorizationKey:字符串;
过程SetClientID(常量值:字符串);
过程SetClientSecret(常量值:字符串);
平民的
{公开声明}
构造函数创建(AOwner:TComponent);推翻
毁灭者毁灭;推翻
函数翻译(文本:字符串):字符串;
属性ClientID:字符串读取fClientID写入SetClientID;
属性ClientSecret:字符串读取fClientSecret写入SetClientSecret;
属性SourceLanguage:字符串读取FSourcelLanguage写入FSourcelLanguage;
属性TargetLanguage:字符串读取fTargetLanguage写入fTargetLanguage;
终止
//http://oauthdevconsole.cloudapp.net/PartialOAuth
实施
使用
HTTPApp、DBXJSON、ComObj、变体;
{TMSTranslator}
构造函数TMSTranslator.Create(AOwner:TComponent);
开始
继承;
IdHTTP:=TIdHTTP.Create(nil);
idsslohandlersocketopenssl:=TIdSSLIOHandlerSocketOpenSSL.Create(nil);
IdHTTP.Request.ContentType:=“应用程序/x-www-form-urlencoded”;
idHTTP.HandlerRedirects:=True;
IdHTTP.Request.CustomHeaders.FoldLines:=false;//避免用空格分隔
IdHTTP.IOHandler:=IdSSLIOHandlerSocketOpenSSL;
终止
析构函数;解构;
开始
IdHTTP.Free;
IdSSLIOHandlerSocketOpenSSL.Free;
继承;
终止
程序TMSTranslator.SetClientID(常量值:字符串);
开始
如果是fClientID值,则
AuthKey:='';
fClientID:=值;
终止
过程TMSTranslator.SetClientSecret(常量值:字符串);
开始
如果是FClientCret值,则
AuthKey:='';
FClientCret:=值;
终止
函数TMSTranslator.GetAuthorizationKey:字符串;
变量
字符串列表:TStringList;
StringStream:TStringStream;
ljsonobject:TJSONObject;
LJsonValue:TJSONValue;
开始
如果AuthKey='',则开始
如果fClientID='',则
引发异常。创建('需要分配属性fClientID');
如果fClientSecret='',则
引发异常。创建('需要分配属性fClientSecret');
StringList:=TStringList.Create;
StringStream:=TStringStream.Create(“”,TEncoding.UTF8);
尝试
Add('grant_type=client_credentials');
添加('&client_id='+HTTPEncode(fClientID));
添加('&client_secret='+HTTPEncode(fClientSecret));
StringList.Add('&scope='+HTTPEncode('http://api.microsofttranslator.com'));
StringStream.WriteString(StringList.text);
IdHTTP.Request.CustomHeaders.Clear;
结果:=idHTTP.Post('https://datamarket.accesscontrol.windows.net/v2/OAuth2-13",;
LJsonObj:=TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(result),0)作为TJSONObject;
尝试
LJsonValue:=LJsonObj.Get('access_token').JsonValue;
结果:=LJsonValue.Value;
最后
LJsonObj.Free;
终止
最后
StringList.free;
StringStream.free;
终止
结束其他
结果:=AuthKey;
终止
函数TMSTranslator.Translate(文本:字符串):字符串;
变量
XmlDoc:OleVariant;
节点:油变异体;
StringStream:TStringStream;
Url:string;
常数
Msxml2_DOMDocument='Msxml2.DOMDocument.6.0';
开始
AuthKey:=GetAuthorizationKey;
如果文本为“”,则开始
如果fSourceLanguage='',则
引发异常。创建('需要分配属性fSourceLanguage');
如果fTargetLanguage='',则
引发异常。创建('需要指定属性语言');
Url:=格式('http://api.microsofttranslator.com/v2/Http.svc/Translate?text=%s&from=%s&to=%s“,[HTTPEncode(文本),F源语言,F源语言];
IdHTTP.Request.CustomHeaders.Clear;
IdHTTP.Request.CustomHeaders.AddValue('Authorization','Bearer'+AuthKey);
StringStream:=TStringStream.Create(“”,TEncoding.UTF8);
尝试
Get(Url,StringStream);
StringStream.位置:=0;
结果:=StringStream.ReadString(StringStream.size);
XmlDoc:=CreateOleObject(Msxml2_DOMDocument);
尝试
XmlDoc.Async:=False;
LoadXML(结果);
如果是(XmlDoc.parseError.errorCode 0),则
引发异常.CreateFmt('Xml数据中的错误:%s',[XmlDoc.parseError]);
节点:=XmlDoc.documentElement;
如果不是VarIsClear(节点),则开始
结果:=XmlDoc.Text;
如果pos('translateAppiexceptionMethod',result)>0,则
结果:='';
终止
最后
XmlDoc:=未分配;
终止
结束其他
结果:='';
终止
====================
变量
MSTranslator:TMSTranslator;
开始
MSTranslator:=tmsplator.Create(nil);
尝试
MSTranslator.ClientID:=“YourClientHere”;
MSTranslator.ClientSecret:=“YourClientSecretHere”;
MSTranslator.SourceLanguage:=“en”;
MSTranslator.TargetLanguage:=“th”;
ShowMessage(MSTranslator.Translate('Hello'));
最后
lHTTP.Request.CustomHeaders.FoldLines := false; // avoid split by white space
lHTTP.Request.CustomHeaders.AddValue('Authorization', 'Bearer ' + AuthKey);
myStream = TStringStream.Create;
try
lHTTP.Get(uri, stream);
stream.Position := 0;
Result := stream.ReadString(stream.size);
finally
FreeAndNil(lHTTP);
FreeAndNil(stream);
end;
unit MSTranslationv2;
interface
uses
Classes, SysUtils,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,
IdHTTP, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL,
IdSSLOpenSSL;
type
TMSTranslator = class(TComponent)
IdHTTP: TIdHTTP;
IdSSLIOHandlerSocketOpenSSL: TIdSSLIOHandlerSocketOpenSSL;
private
fSourceLanguage: string;
fClientID: string;
fClientSecret: string;
fTargetLanguage: string;
AuthKey : string;
{ Private declarations }
function GetAuthorizationKey: string;
procedure SetClientID(const Value: string);
procedure SetClientSecret(const Value: string);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Translate(Text: string): string;
property ClientID: string read fClientID write SetClientID;
property ClientSecret: string read fClientSecret write SetClientSecret;
property SourceLanguage: string read fSourceLanguage write fSourceLanguage;
property TargetLanguage: string read fTargetLanguage write fTargetLanguage;
end;
//http://oauthdevconsole.cloudapp.net/PartialOAuth
implementation
uses
HTTPApp, DBXJSON, ComObj, Variants;
{ TMSTranslator }
constructor TMSTranslator.Create(AOwner: TComponent);
begin
inherited;
IdHTTP := TIdHTTP.Create(nil);
IdSSLIOHandlerSocketOpenSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
IdHTTP.Request.ContentType := 'application/x-www-form-urlencoded';
idHTTP.HandleRedirects := True;
IdHTTP.Request.CustomHeaders.FoldLines := false; // avoid split by white space
IdHTTP.IOHandler := IdSSLIOHandlerSocketOpenSSL;
end;
destructor TMSTranslator.Destroy;
begin
IdHTTP.Free;
IdSSLIOHandlerSocketOpenSSL.Free;
inherited;
end;
procedure TMSTranslator.SetClientID(const Value: string);
begin
if fClientID <> Value then
AuthKey:= '';
fClientID := Value;
end;
procedure TMSTranslator.SetClientSecret(const Value: string);
begin
if fClientSecret <> Value then
AuthKey := '';
fClientSecret := Value;
end;
function TMSTranslator.GetAuthorizationKey: string;
var
StringList : TStringList;
StringStream: TStringStream;
LJsonObj : TJSONObject;
LJsonValue : TJSONValue;
begin
if AuthKey = '' then begin
if fClientID = '' then
raise Exception.Create('Property fClientID needs to be assigned.');
if fClientSecret = '' then
raise Exception.Create('Property fClientSecret needs to be assigned.');
StringList := TStringList.Create;
StringStream := TStringStream.Create('', TEncoding.UTF8);
try
StringList.Add('grant_type=client_credentials');
StringList.Add('&client_id='+ HTTPEncode(fClientID) );
StringList.Add('&client_secret='+ HTTPEncode(fClientSecret));
StringList.Add('&scope='+ HTTPEncode('http://api.microsofttranslator.com'));
StringStream.WriteString(StringList.text);
IdHTTP.Request.CustomHeaders.Clear;
result := idHTTP.Post('https://datamarket.accesscontrol.windows.net/v2/OAuth2-13', StringStream);
LJsonObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(result),0) as TJSONObject;
try
LJsonValue :=LJsonObj.Get('access_token').JsonValue;
result := LJsonValue.Value;
finally
LJsonObj.Free;
end;
finally
StringList.free;
StringStream.free;
end;
end else
result := AuthKey;
end;
function TMSTranslator.Translate(Text: string): string;
var
XmlDoc: OleVariant;
Node: OleVariant;
StringStream : TStringStream;
Url: string;
const
Msxml2_DOMDocument = 'Msxml2.DOMDocument.6.0';
begin
AuthKey := GetAuthorizationKey;
if Text <> '' then begin
if fSourceLanguage = '' then
raise Exception.Create('Property fSourceLanguage needs to be assigned.');
if fTargetLanguage = '' then
raise Exception.Create('Property fTargetLanguage needs to be assigned.');
Url := format('http://api.microsofttranslator.com/v2/Http.svc/Translate?text=%s&from=%s&to=%s', [HTTPEncode(Text), fSourceLanguage, fTargetLanguage]);
IdHTTP.Request.CustomHeaders.Clear;
IdHTTP.Request.CustomHeaders.AddValue('Authorization', 'Bearer ' + AuthKey);
StringStream := TStringStream.Create('', TEncoding.UTF8);
try
IdHTTP.Get(Url, StringStream);
StringStream.Position := 0;
Result := StringStream.ReadString(StringStream.size);
XmlDoc:= CreateOleObject(Msxml2_DOMDocument);
try
XmlDoc.Async := False;
XmlDoc.LoadXML(Result);
if (XmlDoc.parseError.errorCode <> 0) then
raise Exception.CreateFmt('Error in Xml data: %s',[XmlDoc.parseError]);
Node:= XmlDoc.documentElement;
if not VarIsClear(Node) then begin
Result:= XmlDoc.Text;
if pos('TranslateApiExceptionMethod', result) >0 then
Result := '';
end;
finally
XmlDoc := Unassigned;
end;
end else
result := '';
end;
====================
var
MSTranslator: TMSTranslator;
begin
MSTranslator := TMSTranslator.Create(nil);
try
MSTranslator.ClientID := 'YourClientIDHere';
MSTranslator.ClientSecret := 'YourClientSecretHere';
MSTranslator.SourceLanguage := 'en';
MSTranslator.TargetLanguage := 'th';
ShowMessage(MSTranslator.Translate('Hello'));
finally
MSTranslator.free;
end;
end;