使用Delphi获取Microsoft Translation时获得400响应 [英] Getting 400 response when using Delphi to get Microsoft Translation
问题描述
我在Azure上注册了我的应用程序,收到了一个秘密并成功运行了MSDN提供的c#和php示例,我甚至在我的Delphi 2010中使用TIdHTTP获得了访问令牌: / 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
结果:= idHTTP.Post(uri,lParamList);
最后
FreeAndNill(idHTTP);
FreeAndNill(paramsList);
end;
然后我使用副本提取响应的令牌部分。现在,当我尝试获取实际翻译时,我收到错误请求错误。
以下是我的尝试:
idHTTP.Request.CustomHeaders.AddValue('Authorization',headers);
尝试
stringResult:= idHTT.Get('http://api.microsofttranslator.com/v2/Http.svc/Translate?text=Gracias%20a%20l%20vida&from=es&to = EN');
最后
FreeAndNil(idHTTP);
end;
我也无法使用post获得响应:
paramList:= TStiringList.Create ;
paramList.Add('Authorization = Bearer'+ Token);
try
idHTTP.Post(uri,paramList);
最后
...
仍然相同的响应 - 400,请协助,因为我真的想在我的应用程序中集成此服务。
这应该可以帮到你。
nit MSTranslationv2 ;
接口
使用
课程 , SysUtils ,
IdBaseComponent , IdComponent , IdTCPConnection , IdTCPClient ,
IdHTTP , IdIOHandler , IdIOHandlerSocket , IdIOHandlerStack , IdSSL ,
IdSSLOpenSSL ;
类型 TMSTranslator = 类 ( TComponent )
IdHTTP : TIdHTTP ;
IdSSLIOHandlerSocketOpenSSL : TIdSSLIOHandlerSocketOpenSSL ;
私人
fSourceLanguage : 字符串 ;
;&NBSP; fClientID : 字符串 ;
;&NBSP; fClientSecret : 字符串 ;
;&NBSP; fTargetLanguage : 字符串 ;
;&NBSP; AuthKey : 字符串 ;
{私人声明}
功能 GetAuthorizationKey :
字符串 ;
程序 SetClientID ( const 值 :
字符串 );
程序 SetClientSecret ( const 值 :
string );
公众
{公开声明}
构造函数 创建 ( AOwner : TComponent ); 覆盖 ;
析构函数 销毁 ; 覆盖 ;
功能 翻译 ( 文字 :
字符串 ): 字符串 ;
属性 ClientID :
字符串 读取fClientID写入SetClientID ;
属性 ClientSecret :
字符串 读取fClientSecret写入SetClientSecret ;
属性 SourceLanguage :
字符串 读取fSourceLanguage写入fSourceLanguage ;
属性 TargetLanguage :
字符串 读取fTargetLanguage写入fTargetLanguage ;
结束 ;
// http: //oauthdevconsole.cloudapp.net/PartialOAuth
实施
使用
HTTPApp , DBXJSON , ComObj , 变体 ;
{TMSTranslator}
构造函数 TMSTranslator 。 创建 ( AOwner : TComponent );
开始
继承 ;
$
IdHTTP := TIdHTTP 。 创建 ( nil );
IdSSLIOHandlerSocketOpenSSL 跨度> <跨度>:= 跨度> <跨度> TIdSSLIOHandlerSocketOpenSSL 跨度> <跨度> 跨度> <跨度>创建跨度> <跨度>(跨度> <跨度>零 );
IdHTTP 。 请求 。 ContentType
:= 'application / x-www-form-urlencoded' ;
idHTTP 。 HandleRedirects :=
真 ;
IdHTTP 。 请求 。 CustomHeaders 。 FoldLines
:= false ;
//避免按空格分割
IdHTTP 。 IOHandler := IdSSLIOHandlerSocketOpenSSL ;
结束 ;
析构函数 TMSTranslator 。 销毁 ;
开始
IdHTTP 。 免费 ;
IdSSLIOHandlerSocketOpenSSL 。 免费 ;
$
继承 ;
结束 ;
程序 TMSTranslator 。 SetClientID ( const 值 :
string );
开始
&NBSP; 如果 fClientID <> 价值
则
AuthKey := '' ;
fClientID := 值 ;
结束 ;
程序 TMSTranslator 。 SetClientSecret ( const 值 :
string );
开始
如果 fClientSecret <> 价值
则
AuthKey := '' ;
fClientSecret := 值 ;
结束 ;
功能 TMSTranslator 。 GetAuthorizationKey :
字符串 ;
var
StringList : TStringList ;
StringStream : TStringStream ;
LJsonObj : TJSONObject ;
LJsonValue : TJSONValue ;
开始
如果 AuthKey = ''
然后 开始
;&NBSP; 如果 fClientID =
'' 然后
提升 例外 。 创建 ( '属性fClientID需要分配。' );
如果 fClientSecret =
'' 然后
提升 例外 。 创建 ( '属性fClientSecret需要分配。' );
StringList := TStringList 。 创建 ;
StringStream := TStringStream 。 创建 ( ' ' , TEncoding 。 UTF8 );
尝试
。StringList的跨度> <跨度> 跨度> <跨度>添加跨度> <跨度>(跨度> <跨度> 'grant_type = client_credentials'跨度> <跨度>); 跨度>
。StringList的跨度> <跨度> 跨度> <跨度>添加跨度> <跨度>(跨度> <跨度> '&安培; CLIENT_ID ='跨度> <跨度> + 跨度> HTTPEncode ( fClientID )
);
。StringList的跨度> <跨度> 跨度> <跨度>添加跨度> <跨度>(跨度> <跨度> '&安培; client_secret ='跨度> <跨度> + 跨度> HTTPEncode ( fClientSecret ));
  ;&NBSP;&NBSP; 。StringList的跨度> <跨度> 跨度> <跨度>添加跨度> <跨度>(跨度> <跨度> '&安培;范围='跨度> <跨度> + 跨度> HTTPEncode ( 'http://api.microsofttranslator.com' ));
字符串流跨度> <跨度> 跨度> <跨度> WriteString 跨度> <跨度>(跨度> <跨度>的StringList 跨度> <跨度> 跨度> <跨度>文本 );
IdHTTP 跨度> <跨度> 跨度> <跨度>请求跨度> <跨度> 跨度> <跨度> CustomHeaders 跨度> <跨度> 跨度> <跨度>清除 ;
结果 := idHTTP 。 发布 ( ' https://datamarket.accesscontrol.windows.net/v2/OAuth2-13' , StringStream );
LJsonObj := TJSONObject 。 ParseJSONValue ( TEncoding 跨度> <跨度> 跨度> <跨度> ASCII 跨度> <跨度> 跨度> <跨度> GetBytes会跨度> <跨度>(跨度> <跨度>结果 ), 0 )
as TJSONObject ;
尝试
LJsonValue := LJsonObj 。 获取 ( ' access_token' )。 JsonValue ;
&NBSP;&NBSP;&NBSP;结果 := LJsonValue 。 值 ;
<
LJsonObj 。 免费 ;
结束 ;
终于
StringList 。 免费 ;
StringStream 。 免费 ;
结束 ;
结束 其他
结果 := AuthKey ;
结束 ;
功能 TMSTranslator 。 翻译 ( 文字 :
字符串 ): 字符串 ;
var
XmlDoc : OleVariant ;
节点 : OleVariant ;
StringStream : TStringStream ;
网址 : 字符串 ;
const
Msxml2 _ DOMDocument =
'Msxml2.DOMDocument.6.0' ;
开始
AuthKey := GetAuthorizationKey ;
  ; 如果 文字 <>
'' 然后 开始
如果 fSourceLanguage =
'' 然后
提升 异常 。 创建 ( '属性fSourceLanguage需要分配。' );
如果 fTargetLanguage =
'' 然后
提升 例外 。 创建 ( '属性fTargetLanguage需要分配。' );
网址 := 格式 ( 'http://api.microsofttranslator.com/v2/Http.svc/翻译?text =%s& from =%s& to =%s' ,
[ HTTPEncode ( 文本 ), fSourceLanguage , fTargetLanguage ]);
IdHTTP 跨度> <跨度> 跨度> <跨度>请求跨度> <跨度> 跨度> <跨度> CustomHeaders 跨度> <跨度> 跨度> <跨度>清除 ;
IdHTTP 跨度> <跨度> 跨度> <跨度>请求跨度> <跨度> 跨度> <跨度> CustomHeaders 跨度> <跨度> 跨度> <跨度>的AddValue ( '授权' ,
'承担' + AuthKey );
StringStream := TStringStream 。 创建 ( ' ' , TEncoding 。 UTF8 );
尝试
IdHTTP 。 获取 ( 网址 , StringStream );
StringStream 。 职位
:= 0 ;
结果 := StringStream 。 ReadString ( StringStream 。 尺寸 );
&NBSP;&NBSP;&NBSP;&NBSP; XmlDoc := CreateOleObject ( Msxml2 _ DOMDocument );
尝试
XmlDoc 。 异步
:= 错误 ;
。xmlDoc中跨度> <跨度> 跨度> <跨度> loadXML的跨度> <跨度>(跨度> <跨度>结果跨度> <跨度>); 跨度> <跨度>
如果 ( XmlDoc 。 parseError 。 errorCode
<> 0 )
然后
  ;&NBSP; 提升 例外 。 CreateFmt ( '错误Xml数据:%s' ,[ XmlDoc 。 parseError ]);
节点 := XmlDoc 。 documentElement ;
如果 不 VarIsClear ( 节点 )
然后 开始
结果 := XmlDoc 。 文字 ;
如果 pos ( 'TranslateApiExceptionMethod' , 结果 )
> 0 然后
结果
:= '' ;
结束 ;
<
XmlDoc := 未分配 ;
  ; 结束 ;
结束 其他
结果 := '' ;
结束 ;
===== ===============
var
MSTranslator : TMSTranslator ;
开始
MSTranslator := TMSTranslator 。 创建 ( nil );
尝试
MSTranslator 。 ClientID :=
'YourClientIDHere' ;
MSTranslator 。 ClientSecret :=
'YourClientSecretHere' ;
MSTranslator 。 SourceLanguage :=
'en' ;
MSTranslator 。 TargetLanguage :=
'th' ;
ShowMessage 跨度> <跨度>(跨度> <跨度> MSTranslator 跨度> <跨度> 跨度> <跨度>翻译跨度> <跨度>(跨度> <跨度>'你好' ));
终于
MSTranslator 。 免费 ;
结束 ;
结束 ;
I had registered my Application at Azure, received a secret and successfully ran both the c# and php samples provided by MSDN, I even got an access token using TIdHTTP with my Delphi 2010:
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;
I then extract the token part of the response using copy. Now, when I try to get the actual translation I receive a Bad Request error. Here is what I try:
idHTTP.Request.CustomHeaders.AddValue('Authorization', headers); try stringResult := idHTT.Get('http://api.microsofttranslator.com/v2/Http.svc/Translate?text=Gracias%20a%20l%20vida&from=es&to=en'); finally FreeAndNil(idHTTP); end;
I also failed getting a response using post:
paramList := TStiringList.Create; paramList.Add('Authorization= Bearer ' + Token); try idHTTP.Post(uri, paramList); finally ...
Still same response - 400, Please assist as I would really like to integrate this service in my application.
This should help you.
nit 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;
这篇关于使用Delphi获取Microsoft Translation时获得400响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!