The post title is a set of key words I used for googling to find answer. Basically, due to not familiar with protocols and few explicit explanation out there, the whole finding really took a while.
Perl sample code:
http://search.cpan.org/dist/WebService-Google-Language-0.09/lib/WebService/Google/Language.pm
this is Perl translation module utilizing google language Ajax api.
When encoded url with translation text is less than 2000 something or Maximum URL length set by google server, this module uses GET method.
When translation test is between 2000 and 5000, this module will put encoded translation text, api version, and langpair etc in body and send by POST.
You can download Perl from (http://www.perl.org/get.html) and install this module.
Python sample code:
POST method
First please download http://code.google.com/p/python-rest-client/
############################
#POST method
############################
from restful_lib import Connection
import urllib
conn = Connection('http://ajax.googleapis.com/ajax/services/language');
query = {'v':'1.0', 'langpair':'en|de','q':'hello world'};
print conn.request_post("/translate",body=urllib.urlencode(query), headers={'referer':'http://example.com', "content-type":"application/x-www-form-urlencoded" ,"charset":"UTF-8"})
#############################
notes:
1. query needs to be encoded as a string 'q=hello+world&langpair=en%7Cde&v=1.0' with urlencode()
2. "content-type":"application/x-www-form-urlencoded" ,"charset":"UTF-8" shold be added to headers to tell server how 'body' is encoded.
Without them, you will get 'invalid version' error in response.
3. based on perl module description (http://search.cpan.org/dist/WebService-Google-Language-0.09/lib/WebService/Google/Language.pm#CONSTRUCTOR)
header 'referer':'http://example.com' is mandatory, because Google demands a "valid and accurate http referer header" in requests to their service.
4. If you want to use it one google app engine, please use 'from gae_restful_lib import GAE_Connection as Connection' instead ( http://code.google.com/p/python-rest-client/wiki/REST_for_Google_App_Engine )
5. Please try a long translation text, after you get sample code work.
BTW, here is GET method sample code
############################
#POST method
############################
from restful_lib import Connection
print conn.request_get("/translate", args={'v':'1.0','langpair':'en|de','q':'Hello'}, headers={'referer':'http://example.com','Accept':'text/json'})
#############################
useful tool for restful testing:
http://code.google.com/p/rest-client/
Chef
my ads:
U.S. Immigration Guide
http://visachoice.appspot.com
Monday, May 11, 2009
Subscribe to:
Comments (Atom)