昨天 晚上 一个朋友告诉我说一个 游戏充值接口的用户验证采用ajax方法,问题是对方接口需要post方式,而且是跳转的,因为ajax机制的约束不允许php内部又跳转.这样不能获得返回值.我建议他直接在ajax端采用post,他嫌麻烦. 那成,今天早上就用curl 写了个 不跳转的模拟post.
简单代码如下:
- <script>
- $.ajax({url:'http://xxx.xxx.com/sendpost.php',
- type: 'GET',
- dataType: 'json',
- timeout: 3000,
- cache:false,
- error: function(){
- alert("系统错误...");
-
- },
- success: function(data){
- $("#value").html(data.log);
-
- }
- });
- </script>
sendpost.php
- <?php
- $url = 'http://xxx.xxx.com/work.php'; //psot的目标页面
- $postDate ='user='."cyd&age=25"; //post 参数
- $curlObj = curl_init() ;
- curl_setopt($curlObj, CURLOPT_URL,$url) ;
- curl_setopt($curlObj, CURLOPT_POSTFIELDS,$postDate) ;
- $reruenValue = curl_exec($curlObj) ;
- curl_close($curlObj) ;
- ?>
work.php
- <?php
- echo json_encode(array('success'=>'false','log'=>implode(",",$_POST))); //我写的一个简单的json 格式的返回值.
- ?>
之前的im机器人是用c的system调用shell的curl来实现数据传送。测试了两天感觉上不是很舒服。决定调整为c的libcurl API发送数据。
就这个小小的调整,涉及到一堆的修改。
最主要的如下:
1 制作 curl发送的动态链接库 so文件
2 修改im机器人的makefile 文件
curl 发送的so动态连接库:
curl_so_head.h
#include “stdio.h”
#include “curl/curl.h”
#include “stdlib.h”
#include “string.h”
#include “dlfcn.h”
void c2(char *msg,char *from,char *robot); // 设置了msg:消息 from:来源 robot:机器人类型
curl_so.c
#include “curl_so_head.h”
void c2(char *msg,char *from,char *robot)
{
CURL *curl;
CURLcode res;
char *s=”&msg=”;
char *s1=”&from=”;
char *s2=”&robot=”;
char pp[200];
strcpy(pp,s);
strcat(pp,msg);
strcat(pp,s1);
strcat(pp,from);
strcat(pp,s2);
strcat(pp,robot);
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL,”http://xxxx.xxx.xxx.php”);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS,pp);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
}
这个是发送调用程序:
void *SoLib;
int (*So)();
SoLib=dlopen(“so_curl.so”,RTLD_LAZY); //so_curl.so是上面操作生成的so文件
So = dlsym( SoLib, “c2″);
(*So)( msg,from,robot); //msg,from,robot表示需要的 消息 来源 robot 机器人类型
修改makefile文件 主要是要在 gcc 后面加上 -ldl 参数 .
ok 目前这项应用就到此吧。后期可能还要加新东西。