Web backend Language impersonation HTTP request (with username and password) instance code Daquan

Source: Internet
Author: User
Tags ruby on rails

RESTful API is currently a relatively mature set of Internet Application API design theory. With the mature and popular of restful APIs, the application development needs to invoke the RESTful API interface in the way of simulating HTTP request, and after a period of time IBM's cloud platform Blumemix the application of learning and language translation service, accumulated Java, ASP. Nodejs, Go, PHP, Python, Ruby and other languages call the rest API method, here together, and share with you.

For RESTful APIs Please refer to: Understanding RESTful architecture, RESTful API Design Guide


Java in this area of the jar package should be more, such as httpclient, I use the most basic:

The authentication information object that contains the user name and password to access the translation service              Authenticator auth = new Myauthenticator ("username", "password");              Authenticator.setdefault (auth);                            The connection between open and URL              httpsurlconnection connection = (httpsurlconnection) realurl.openconnection ();              Connection.setdoinput (true);                Connection.setdooutput (TRUE);//Allow connection to submit information                     Connection.setrequestmethod ("GET");                            Establish the actual connection              Connection.connect ();  
Related examples: Java in the REST API use example-based on cloud Platform + cloud services to build their own online translator tool


Asp. Net uses the System.Net.Http.HttpClient class to implement API calls:

System.Net.Http.HttpClient HttpClient = new System.Net.Http.HttpClient ()//Convert service voucher to BASE64 encoded format byte[] auth = Encoding.UTF8.GetBytes ("User name: Password"); String auth64 = convert.tobase64string (auth);//Create and specify service credentials, authentication scheme is BasichttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue ("Basic", auth64); retstring = await httpclient.getstringasync (URI);

Related examples: Asp.net5 REST API Use example-Build your own online translator tool based on cloud Platform + cloud service


PHP uses the famous curl to implement API calls:

$ch = Curl_init ();  curl_setopt ($ch, Curlopt_url, $url);  curl_setopt ($ch, Curlopt_returntransfer, 1);  The HTTPS request must have the following two items set  curl_setopt ($ch, curlopt_ssl_verifyhost, 0);  curl_setopt ($ch, Curlopt_ssl_verifypeer, FALSE);    Set the voucher  curl_setopt ($ch, curlopt_userpwd, ' Your user name: your password ');    Execute request  
Related examples: IBM's Cloud Platform Bluemix experience-creating PHP Web applications, adding and using language translation services


Using standard library urllib2 in Python to implement API calls

Passman = Urllib2. Httppasswordmgrwithdefaultrealm () #创建域验证对象  Passman.add_password (None, sURL, "Translation service username", "password") #设置域地址, username and password  Auth_handler = Urllib2. Httpbasicauthhandler (Passman) #生成处理与远程主机的身份验证的处理程序  opener = Urllib2.build_opener (Auth_handler) # Returns a Openerdirector instance  Urllib2.install_opener (opener) #安装一个openerDirector实例作为默认的开启者.  response = Urllib2.urlopen (sURL) #打开URL链接, return response object  rescontent = Response.read () #读取响应内容  
Related examples: Using the rest API in the Python Web--Build your own online translator tool based on cloud Platform + cloud services


Ruby uses the Net::http class to implement API calls

http = net::http.new (uri.host, uri.port)  Http.use_ssl = True  Http.verify_mode = Openssl::ssl::verify_none  request = net::http::get.new (Uri.request_uri)  Request.basic_auth "username", "password"  

Related examples: Ruby on Rails REST API Usage Example-build your own online translator tool based on cloud Platform + cloud service


The go language uses the Net/http package to implement API calls, which has the advantage that we can write the username and password directly in the URL

url = "https://User name: password @gateway.watsonplatform.net/language-translation/api/v2/translate?"; RESP, err: = http. Get (URL)  //Send HTTP GET request  if err! = Nil {  FMT. fprintf (W, err. Error ())  return  }  if resp! = Nil && resp. Body! = Nil {  Defer resp. Body.close ()  }  if resp. StatusCode! = http. Statusok {  FMT. fprintf (w, errors. New (resp. Status). Error ())  return  }  data, err: = Ioutil. ReadAll (resp. Body)  If err! = Nil {  FMT. fprintf (W, err. Error ())  return  }
Related examples: IBM's Cloud Platform Bluemix experience-Create a Go Language Web application, add and use language translation services


Nodejs using HTTPS packets to implement API calls

Impersonation HTTP GET request Http.get ("https://translation service username: password @gateway.watsonplatform.net/language-translation/api/v2/translate?" + Data, function (gres) {   var body = ';  Gres.on (' Data ', function (d) {  body + = D;   }). On (' End ', function () {    //console.log (gres.headers);    Console.log (body);    Output response content    Res.send ("{\" text\ ": \" "+ Body +" \ "}");})  . On (' Error ', function (e) {   console.log ("Got error:" + e.message);   });

Related examples: Using the rest API in node. JS--Build your own online translator tool based on cloud Platform + cloud services

Web backend Language impersonation HTTP request (with username and password) instance code Daquan

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.