您好,欢迎访问一九零五行业门户网

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

最近在开发一个基于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 responseprint_r($output_response);
原文地址:php语言访问rest api上传图片的解决方案, 感谢原作者分享。
其它类似信息

推荐信息