ruby,python及curl post请求

#飘红部分为变量

test_url="http://test"

body_hash={"value"=>100, "year"=>2014, "month"=>11, "day"=>12, "hour"=>16, "minute"=>9, "second"=>0, "host"=>"test"}

body_json=body_hash.to_json

#for curl

curl -X POST -H "Content-Type:application/json" --connect-timeout 10 -m 20 -d '$body_json' $test_url

#for ruby

def send_data(test_url,body_hash)

    data=body_hash

    data=data.to_json

    puts "data for json is #{data}"

    url = URI.parse(test_url)

    req = Net::HTTP::Post.new(url.path,{'Content-Type' => 'application/json'})

    req.body = data

    begin

        res = Net::HTTP.new(url.host,url.port).start do |http|

            http.read_timeout=5

            http.request(req)

        end

    rescue Exception

        res = ''

        puts "error:#{$!} at:#{$@}!"

        puts "post to dest failed!"

        return 1
    end

    post_res=res.body

    puts "post result is #{post_res}"

end

=================================================

#sms发送短信:

#网关给的api请求key,使用 HTTP Basic Auth 方式进行身份验证,使用api作为验证用户名,API key是验证密码

 api-key=key-14a206a26676b946e8df722axxxxxxxx

#网关请求api地址

 api-url="https://sms-api.xxx.com/v1/send.json"

#短信签名,短信签名指附加在短信内容末尾的署名信息,使用发送者的公司名或产品名,格式为:【XXXXX】

 api-name="【测试】"

#for curl

 curl -s -k --user api:$api-key $api-url -F mobile='12345678901' -F message='Send message for test! $api-name'

#for python

mob="12345678901"

msg="for test"+api-name

def send_messag(mob,msg):
    print mob
    print msg
    resp = requests.post((api-url),
    auth=("api", api-key),
    data={
    "mobile": mob,
    "message": msg
    },timeout=3 , verify=False);
    result = json.loads( resp.content )
    print result

#for php,未测试

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,$api-url);

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 

curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_HTTPAUTH , CURLAUTH_BASIC);

curl_setopt($ch, CURLOPT_USERPWD , 'api:$api-key');

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, array('mobile' => '12345678901','message' => 'test【测试】'));

$res = curl_exec( $ch );

curl_close( $ch );

//$res = curl_error( $ch );

var_dump($res);

================ruby uri====================

require 'uri'

uri = URI("http://foo.com/posts?id=30&limit=5#time=1305298413")
#=> #<URI::HTTP:0x00000000b14880
      URL:http://foo.com/posts?id=30&limit=5#time=1305298413>
uri.scheme
#=> "http"
uri.host
#=> "foo.com"
uri.path
#=> "/posts"

uri.port

#=> "80"
uri.query 
#=> "id=30&limit=5" uri.fragment #=> "time=1305298413"
uri.to_s
#=> "http://foo.com/posts?id=30&limit=5#time=1305298413"

posted on 2014-11-13 10:53  生活费  阅读(5217)  评论(0编辑  收藏  举报

导航