Home  >  Article  >  php教程  >  PHP语言访问REST API上传图片的解决方案

PHP语言访问REST API上传图片的解决方案

WBOY
WBOYOriginal
2016-06-06 20:09:221065browse

最近在开发一个基于HTTPS协议的RESTFul API,在为客户写demo的时候遇到一小点问题,由于PHP的使用经验不足,在写PHP语言的客户端时卡壳了一会,主要遇到的问题是: 如何使用PHP语言访问REST API上传图片? 一般理解先将图片做base64编码,然后将请求json格式

最近在开发一个基于HTTPS协议的RESTFul API,在为客户写demo的时候遇到一小点问题,由于PHP的使用经验不足,在写PHP语言的客户端时卡壳了一会,主要遇到的问题是:

如何使用PHP语言访问REST API上传图片?

一般理解先将图片做base64编码,然后将请求json格式化,通过HTTPS POST到后端服务器,结果我的后端服务报错含有非法base64字符\,用PHP的stripslashes转义上传成功。

总结一下,其实技术上遇到问题会很多,为什么牛人、老手可以快速解决,而新人往往需要更多时间或请教别人。主要在于两点:

1、耐心。遇到问题先通过搜索引擎查找,不要一上来就抱着着急或者消极的态度。

2、手段。日志,debug,stacktrace,追踪代码都是可以利用的手段,记住没有无缘无故的问题,出现了问题,99%都是自己使用的问题。

3、洞察力。这就是需要经验的辅助了,如何缩小问题的scope?如何快速定位问题的root cause?如何找出有效解决问题的手段都是需要积累的。

啰嗦了这么半天直接上代码了:)

class Api_Client_Core {
 
	private $url;
 
	private $ch;
 
	public function __construct($serviceName) {
		$this->url = 'http://api.test.com' . $serviceName;
		$this->ch = curl_init($this->url);
		curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'POST');
		curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, true); //开始https支持
		curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, true);
		curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
	}
 
	public function post($request) {
		// Show service definition
		print('----------service url-----------');
		print_r($this->getUrl());
		print('----------service request json-----------');
		print_r($request);
 
		curl_setopt($this->ch, CURLOPT_POSTFIELDS, $request);
 
		$result = curl_exec($this->ch);
 
		return $result;
	}
 
	public function getUrl() {
		return $this->url;
	}
 
}
 
 
class ProfileAddService extends Api_Client_Core {
	public function __construct() {
		parent::__construct('/profile/add');
	}
}
 
// New service
$service = new ProfileAddService();
 
// New request
$file = '960_90.jpg';
$image = file_get_contents($file);
$base64image = base64_encode($image);
 
// Call service
$output_response = $service->post(stripslashes(json_encode($base64image)));
 
// Print response
print_r($output_response);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn