最近在工作中需要请求第三方的一个java版的接口,起初是使用数组进行传参,代码写完之后发现接口死活调试不通,总是提示传参为空,纠结了很久之后,决定尝试使用字符串传参的方式来请求接口,没想到这次居然调试成功了,这让我有了研究这两者究竟有何区别的兴趣。
本地的测试代码如下:
curl.php
<code><span><span><?php </span><span><span>function</span><span>curl_post</span><span>(<span>$url</span>, <span>$data</span>)</span>{</span><span>$ch</span> = curl_init(); curl_setopt(<span>$ch</span>, CURLOPT_URL, <span>$url</span>); curl_setopt(<span>$ch</span>, CURLOPT_RETURNTRANSFER, <span>1</span>); curl_setopt(<span>$ch</span>, CURLOPT_POST, <span>1</span>); curl_setopt(<span>$ch</span>, CURLOPT_POSTFIELDS, <span>$data</span>); <span>$output</span> = curl_exec(<span>$ch</span>); curl_close(<span>$ch</span>); <span>return</span><span>$output</span>; } <span>$params</span> = <span>array</span>(); <span>$params</span>[<span>'username'</span>] = <span>'ben'</span>; <span>$params</span>[<span>'password'</span>] = <span>'lalala'</span>; print_r(curl_post(<span>'http://localhost/curl/post.php'</span>, <span>$params</span>)); <span>$params</span> = <span>array</span>(); <span>$params</span>[<span>'username'</span>] = urlencode(<span>'ben'</span>); <span>$params</span>[<span>'password'</span>] = urlencode(<span>'lalala'</span>); <span>$paramsStr</span> = <span>"username={$params['username']}&password={$params['password']}"</span>; print_r(curl_post(<span>'http://localhost/curl/post.php'</span>, <span>$paramsStr</span>)); <span>?></span></span></span></code>
post.php
<code><span><?php </span><span>echo</span><span>"-------php://input-----<br>"</span>; var_dump(@file_get_contents(<span>'php://input'</span>)); <span>echo</span><span>"-------post-----<br>"</span>; var_dump(<span>$_POST</span>); <span>echo</span><span>"-------server-----<br>"</span>; var_dump(<span>$_SERVER</span>);</span></code>
执行结果可以参照如下截图:
版权声明:本文为博主原创文章,转载请注明出处和作者名,尊重别人也是尊重自己
以上就介绍了php使用curl的post方法字符串和数组传值的区别,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。