如果您想了解php–Python3:JSONPOST请求没有请求库和pythonpostjson数据的知识,那么本篇文章将是您的不二之选。我们将深入剖析php–Python3:JSONPOST请求没有
如果您想了解php – Python3:JSON POST请求没有请求库和python post json数据的知识,那么本篇文章将是您的不二之选。我们将深入剖析php – Python3:JSON POST请求没有请求库的各个方面,并为您解答python post json数据的疑在这篇文章中,我们将为您介绍php – Python3:JSON POST请求没有请求库的相关知识,同时也会详细的解释python post json数据的运用方法,并给出实际的案例分析,希望能帮助到您!
本文目录一览:- php – Python3:JSON POST请求没有请求库(python post json数据)
- php – 如何在Slim中访问POST请求的JSON请求主体?
- php 网络请求 get请求和post请求
- PHP中的JSON POST请求解析
- Python flask接收json数据,requests发送post请求发送json数据
php – Python3:JSON POST请求没有请求库(python post json数据)
我想只使用本机Python库将JSON编码数据发送到服务器.我喜欢请求,但我根本无法使用它,因为我不能在运行脚本的机器上使用它.我需要在没有的情况下这样做.
newConditions = {"con1":40, "con2":20, "con3":99, "con4":40, "password":"1234"}
params = urllib.parse.urlencode(newConditions)
params = params.encode('utf-8')
req = urllib.request.Request(conditionsSetURL, data=params)
urllib.request.urlopen(req)
我的服务器是本地WAMP服务器.我总是得到一个
urllib.error.HTTPError: HTTP Error 500: Internal Server Error
我100%确定这不是服务器问题,因为同一台机器上具有相同网址的相同数据与同一服务器一起使用请求库和邮递员.
解决方法:
您没有发布JSON,而是发布了application / x-www-form-urlencoded请求.
编码为JSON并设置正确的标题:
import json
newConditions = {"con1":40, "con2":20, "con3":99, "con4":40, "password":"1234"}
params = json.dumps(newConditions).encode('utf8')
req = urllib.request.Request(conditionsSetURL, data=params,
headers={'content-type': 'application/json'})
response = urllib.request.urlopen(req)
演示:
>>> import json
>>> import urllib.request
>>> conditionsSetURL = 'http://httpbin.org/post'
>>> newConditions = {"con1":40, "con2":20, "con3":99, "con4":40, "password":"1234"}
>>> params = json.dumps(newConditions).encode('utf8')
>>> req = urllib.request.Request(conditionsSetURL, data=params,
... headers={'content-type': 'application/json'})
>>> response = urllib.request.urlopen(req)
>>> print(response.read().decode('utf8'))
{
"args": {},
"data": "{\"con4\": 40, \"con2\": 20, \"con1\": 40, \"password\": \"1234\", \"con3\": 99}",
"files": {},
"form": {},
"headers": {
"Accept-Encoding": "identity",
"Connection": "close",
"Content-Length": "68",
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "Python-urllib/3.4",
"X-Request-Id": "411fbb7c-1aa0-457e-95f9-1af15b77c2d8"
},
"json": {
"con1": 40,
"con2": 20,
"con3": 99,
"con4": 40,
"password": "1234"
},
"origin": "84.92.98.170",
"url": "http://httpbin.org/post"
}
php – 如何在Slim中访问POST请求的JSON请求主体?
我只是Slim框架中的新手.我使用Slim框架编写了一个API.
POST应用程序将从iPhone应用程序发送到此API.此POST请求采用JSON格式.
但我无法访问iPhone请求中发送的POST参数.当我尝试打印POST参数的值时,每个参数都得到“null”.
$allPostvars = $application->request->post(); //Always I get null
然后我尝试获取即将到来的请求的主体,将主体转换为JSON格式并将其作为对iPhone的响应发回.然后我得到了参数的值,但它们的格式非常奇怪,如下所示:
"{\"password\":\"admin123\",\"login\":\"admin@gmail.com\",\"device_type\":\"iphone\",\"device_token\":\"785903860i5y1243i5\"}"
所以有一件事是肯定的,POST请求参数将来到这个API文件.虽然在$application-> request-> post()中无法访问它们,但它们正在进入请求正文.
我的第一个问题是如何从请求主体访问这些POST参数,我的第二个问题是为什么请求数据在将请求主体转换为JSON格式后显示为如上所述的奇怪格式?
以下是必要的代码段:
<?PHP
require 'Slim/Slim.PHP';
\Slim\Slim::registerautoloader();
//Instantiate Slim class in order to get a reference for the object.
$application = new \Slim\Slim();
$body = $application->request->getBody();
header("Content-Type: application/json");//setting header before sending the JSON response back to the iPhone
echo json_encode($new_body);// Converting the request body into JSON format and sending it as a response back to the iPhone. After execution of this step I'm getting the above weird format data as a response on iPhone.
die;
?>
解决方法:
一般来说,您可以通过以下两种方式之一单独访问POST参数:
$paramValue = $application->request->params('paramName');
要么
$paramValue = $application->request->post('paramName');
更多信息可在文档中找到:http://docs.slimframework.com/#Request-Variables
在POST中发送JSON时,您必须访问请求正文中的信息,例如:
$app->post('/some/path', function () use ($app) {
$json = $app->request->getBody();
$data = json_decode($json, true); // parse the JSON into an assoc. array
// do other tasks
});
php 网络请求 get请求和post请求
代码记录
<pre>
<?php
header('content-type:application:json;charset=utf8');
header('Access-Control-Allow-Origin:*');
//header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
//访问小程序获取二维码图片试试,听说是二进制图片
qd_code_dsh();
//多店铺二维码 一店一码
function qd_code_dsh(){
$arr = array(
'path' => '/pages/index/index?dsh_id=1','width' => 430,'scene' => 0
);
$path = json_encode($arr);
$post_data=$path;
$url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".get_acce<a href="https://www.jb51.cc/tag/sst/" target="_blank">sst</a>oken();
//$url="https://api.weixin.qq.com/wxa/getwxacode?access_token=".get_acce<a href="https://www.jb51.cc/tag/sst/" target="_blank">sst</a>oken();
$result=api_notice_increment($url,$post_data);
echo $result;
}
function api_notice_increment($url,$data){
$ch = curl_init();
$header = "Accept-Charset: utf-8";
curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank">eto</a>pt($ch,CURLOPT_URL,$url);
curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank">eto</a>pt($ch,CURLOPT_CUST<a href="https://www.jb51.cc/tag/omr/" target="_blank">omr</a>EQUEST,"POST");
curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank">eto</a>pt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank">eto</a>pt($ch,CURLOPT_SSL_VERIFYHOST,CURLOPT_USERAGENT,'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank">eto</a>pt($ch,CURLOPT_FOLLOWLOCATION,1);
curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank">eto</a>pt($ch,CURLOPT_AUTOREFERER,CURLOPT_POSTFIELDS,$data);
curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank">eto</a>pt($ch,CURLOPT_RETURNTRANSFER,true);
$tmpInfo = curl_exec($ch);
// var_dump($tmpInfo);
// exit;
if (curl_errno($ch)) {
return false;
}else{
// var_dump($tmpInfo);
return $tmpInfo;
}
}
/* <a href="https://www.jb51.cc/tag/diaoyong/" target="_blank">调用</a>微信api,<a href="https://www.jb51.cc/tag/huoqu/" target="_blank">获取</a>access_token,有效期7200s -xzz0704 */
function get_acce<a href="https://www.jb51.cc/tag/sst/" target="_blank">sst</a>oken(){
/* 直接返回access_token */
$result = curl_get_https("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxdcdbc3696ede3ec5&secret=b57a681d90f5d8552c1486831241c950");
$res = json_decode($result,true); //json字符串转数组
if($res){
return $res['access_token'];
}else{
return 'api return error';
}
}
function curl_get_https($url){
$curl = curl_init(); // 启动<a href="https://www.jb51.cc/tag/yige/" target="_blank">一个</a>CURL会话
curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank">eto</a>pt($curl,$url);
curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank">eto</a>pt($curl,CURLOPT_HEADER,0);
curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank">eto</a>pt($curl,1);
curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank">eto</a>pt($curl,false); // 跳过证书检查
//curl_s<a href="https://www.jb51.cc/tag/eto/" target="_blank">eto</a>pt($curl,true); // 从证书中检查SSL加密算法是否存在
$tmpInfo = curl_exec($curl); //返回api的json对象
//<a href="https://www.jb51.cc/tag/guanbi/" target="_blank">关闭</a>URL请求
curl_close($curl);
return $tmpInfo; //返回json对象
}
?>
PHP中的JSON POST请求解析
我已经在Java中生成了一个包含JSON对象的HTMLPost请求,并希望在PHP中对其进行解析。
public static String transferJSON(JSONObject j) { HttpClient httpclient= new DefaultHttpClient(); HttpResponse response; HttpPost httppost= new HttpPost(SERVERURL); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("json", j.toString())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); response = httpclient.execute(httppost); }
并在服务器上
<?phpif ($_SERVER[''REQUEST_METHOD''] === ''POST'') { // input = "json=%7B%22locations%22%3A%5B%7B%22..." $input = file_get_contents(''php://input''); // jsonObj is empty, not working $jsonObj = json_decode($input, true);
我猜这是因为JSON特殊字符已编码。
json_decode返回空响应
知道为什么吗?
答案1
小编典典实际上application/json
,您不是在发布实体,而是在发布具有application/x-www-form-urlencoded
单个值对json =(encoded json)的HTTP表单实体()。
代替
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("json", j.toString()));httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
尝试
httppost.setEntity(new StringEntity(j.toString(),"application/json","UTF-8"));
Python flask接收json数据,requests发送post请求发送json数据
目录
flask接收json数据
requests发送post请求发送json数据
flask接收json数据
1. 利用flask的request.form()方法接收:
import json
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
data = request.form['data'] # 获取值
return json.dumps(data,ensure_ascii=False)
2. 利用flask的request.get_data()方法接收
from flask import Flask
app = Flask(__name__)
@app.route("/check/custom/file",methods=["POST"])
def check_custom_file():
set_config = request.get_data()
if set_config is None or set_config == "":
return json_error(403,"Parameter set_config can not be empty.")
set_config = json.loads(set_config)
print(set_config)
return jsonify(status="success")
3. 利用flask的request.args.to_dict()
@app.route('/add2',methods=['GET'])
def Add2():
get_data = request.args.to_dict()# 获取传入的params参数
num1 = get_data.get('num1')
num2 = get_data.get('num2')
return json.dumps(int(num2) + int(num1),ensure_ascii=False)
requests发送post请求发送json数据
1. 将json格式的数据转换成字典类型的数据,调用json.dumps()方法完成传递
import requests
import json
url = 'https://openapi.vmall.com/mcp/offlineshop/getShopList'
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/80.0.3987.163 Safari/537.36'
}
# 将json类型的数据转换成字典类型的数据
data = {
"portal":2,"lang":"zh-CN","country":"CN","brand":1,"province":"山西","city":"太原","pageNo":1,"pageSize":20
}
# 调用json.dumps()方法,将数据以json格式传递
response = requests.post(url=url,headers=headers,data=json.dumps(data))
page_text = response.text
print(page_text)
2. 直接使用post方法,给参数json传入json类型的数据
import requests
url = "http://172.16.12.131:8888/check/custom/file"
header = {
"aaaa": token
}
data = {
"aaa":True,"bbb":False
}
res = requests.post(url=url,headers=header,json=data)
#print(res.content,res.status_code)
print(res.text,res.status_code)
今天关于php – Python3:JSON POST请求没有请求库和python post json数据的介绍到此结束,谢谢您的阅读,有关php – 如何在Slim中访问POST请求的JSON请求主体?、php 网络请求 get请求和post请求、PHP中的JSON POST请求解析、Python flask接收json数据,requests发送post请求发送json数据等更多相关知识的信息可以在本站进行查询。
本文标签: