Web后端语言模拟http请求(带username和password)实例代码大全

RESTful API是眼下比較成熟的一套互联网应用程序的API设计理论。而随着RESTful API的成熟和流行,应用开发方面就须要以模拟http请求的方式来调用RESTful API接口;经过一段时间的IBM的云平台Blumemix的学习及语言翻译服务的应用。积累了Java、ASP.NET、Nodejs、Go、PHP、Python、Ruby等语言调用Rest API的方法,这里整理到一起。和大家分享一下。

有关RESTful API请參考:理解RESTful架构RESTful API 设计指南


Java

Java这方面的Jar包应该比較多。比方HttpClient,我这里使用最主要的:

//认证信息对象,用于包括訪问翻译服务的username和password  
            Authenticator auth = new MyAuthenticator("username", "password");  
            Authenticator.setDefault(auth);  
              
            // 打开和URL之间的连接  
            HttpsURLConnection connection = (HttpsURLConnection)realUrl.openConnection();  
            connection.setDoInput(true);    
            connection.setDoOutput(true);//同意连接提交信息         
            connection.setRequestMethod("GET");  
              
            // 建立实际的连接  
            connection.connect();  
相关实例:Java中REST API使用演示样例——基于云平台+云服务打造自己的在线翻译工具

ASP.NET

ASP.NET中使用System.Net.Http.HttpClient类来实现API调用:

System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
//将服务凭证转换为Base64编码格式
byte[] auth = Encoding.UTF8.GetBytes("username:password");
String auth64 = Convert.ToBase64String(auth);
//创建并指定服务凭证,认证方案为Basic
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", auth64);

retString = await httpClient.GetStringAsync(uri);

相关实例:ASP.NET5 REST API使用演示样例——基于云平台+云服务打造自己的在线翻译工具


PHP

php中使用大名鼎鼎的CURL来实现API调用:

$ch = curl_init();  
curl_setopt($ch, CURLOPT_URL, $url);  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
//https请求必须设置下面两项  
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);  
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  
  
//设置凭证  
curl_setopt($ch, CURLOPT_USERPWD, '您的username:您的password');  
  
//运行请求  
$output = curl_exec($ch); 
相关实例:IBM的云平台Bluemix使用初体验——创建PHP Web 应用程序,加入并使用语言翻译服务


Python

Python中使用标准库urllib2来实现API调用

passman = urllib2.HTTPPasswordMgrWithDefaultRealm() #创建域验证对象  
passman.add_password(None, surl, "翻译服务username", "password") #设置域地址,username及password  
auth_handler = urllib2.HTTPBasicAuthHandler(passman) #生成处理与远程主机的身份验证的处理程序  
opener = urllib2.build_opener(auth_handler) #返回一个openerDirector实例  
urllib2.install_opener(opener) #安装一个openerDirector实例作为默认的开启者。

response = urllib2.urlopen(surl) #打开URL链接,返回Response对象 resContent = response.read() #读取响应内容

相关实例:Python Web中REST API使用演示样例——基于云平台+云服务打造自己的在线翻译工具


Ruby

Ruby使用Net::HTTP类来实现API调用

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"  
response = http.request(request) 

相关实例:Ruby On Rails中REST API使用演示样例——基于云平台+云服务打造自己的在线翻译工具


Go

Go语言使用net/http包来实现API调用,它有个优点是我们能够直接把username和password写在Url中

url = "https://username:password@gateway.watsonplatform.net/language-translation/api/v2/translate?

"; resp, err := http.Get(url) //改送HTTP Get请求 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 }

相关实例:IBM的云平台Bluemix使用初体验——创建Go语言 Web 应用程序,加入并使用语言翻译服务


Nodejs

Nodejs使用https包来实现API调用

//模拟HTTP Get请求 	http.get("https://翻译服务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);  
	  //输出响应内容  
	  res.send("{"text":"" + body + ""}");  
	 });  
}).on('error', function(e) {   
	console.log("Got error: " + e.message);   
});

相关实例:Node.js中REST API使用演示样例——基于云平台+云服务打造自己的在线翻译工具


原文地址:https://www.cnblogs.com/wgwyanfs/p/7291024.html