您的位置:首页 > 编程语言 > Python开发

curl perl python post发送json数据

2017-10-18 21:09 483 查看
curl -XPOST 'http://192.168.137.2:9200/library/books/1000' -d '{
"title":"Elasticsearch test",
"name" :{  "first":"zhao",  "last":"yangjian"  },
"publish_date":"2017-11-29",
"price":"1000"  }'

{"_index":"library","_type":"books","_id":"1000","_version":1,"_shards":{"total":2,"successful":1,"failed":0},"created":true
[elk@node01 ~]$

perl 版本:

##发送消息
use  LWP::UserAgent;
use LWP;
use Encode;
use LWP::Simple;
use LWP::UserAgent;
use HTTP::Cookies;
use HTTP::Headers;
use HTTP::Response;
use Encode;
use URI::Escape;
use URI::URL;
use JSON;
use Data::Dumper;
my $ua = LWP::UserAgent->new;
$ua->agent("Mozilla/5.0 (Windows NT 6.1; rv:30.0) Gecko/20100101 Firefox/30.0");
my $cookie_jar = HTTP::Cookies->new(
file=>'lwp_cookies.txt',
autosave=>1,
ignore_discard=>1);
$ua->cookie_jar($cookie_jar);
my     $login_url ="http://192.168.137.2:9200/library/books/1001";
my $post = {
title=>"Elasticsearch 1001",
name => {

"first"=> "zhao",
"last"=>"yangjian"
},
"publish_date"=>"2017-01-29",
"price"=>"1001"
}  ;
use JSON qw(encode_json);
$json_string = encode_json($post);

my $req = HTTP::Request->new(
'POST' => $login_url
);
$req->referer("https://wx.qq.com/?&lang=zh_CN");
$req->content_type('application/json; charset=UTF-8')
;    #post请求,如果有发送参数,必须要有这句
$req->content("$json_string");    #发送post的参数
my $res = $ua->request($req);
print $res->content();            #获取的是响应正文

python 版:
#!/usr/bin/env python
#  -*- coding:utf-8 -*-
# File http_post.py

import urllib
import urllib2
import json

def http_post():
url = 'http://192.168.137.2:9200/library/books/1002'
values =  {
'title':"Elasticsearch 1002",
'name' : {

"first": "zhao",
"last":"yangjian"
},
"publish_date":"2017-01-29",
"price":"1002"
}

jdata = json.dumps(values)  # 对数据进行JSON格式化编码
req = urllib2.Request(url, jdata)  # 生成页面请求的完整数据
response = urllib2.urlopen(req)  # 发送页面请求
return response.read()  # 获取服务器返回的页面信息

resp = http_post()
print resp




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: