HTTP POST API:apache环境下POST JSON格式参数使用json.dumps()出错

最近发生了一个神奇的故障。还没有定位到最终原因。暂时规避解决。记录如下.

客户端环境:MAC

服务器端环境:Apache Tomcat/7.0.59

 

客户端代码(python 2.7.8):

rv = requests.post(createConfigUrl, data=json.dumps(data), headers=header)

header = {

    'Content-Type': 'application/json'

}

data = {
        "a": a,
        "b": b,
        "c": c,
        "param": json.dumps(param)

    }

服务器返回HTTP 400:The request sent by the client was syntactically incorrect.

 

解决方案:

rv = requests.post(createConfigUrl, json=data, headers=header)

据资深工程师猜测:这个是JAVA服务器端和PYTHON服务器端的区别;根因尚未定位

#!/usr/bin/python3 # coding=utf-8 from zaixian_cas_login import HttpResponseProcessor from zaixian_cas_login import get_credentials import sys import time import requests import json from urllib.parse import urlparse, urljoin SUC_RES = { 'resCode': 200, 'resTime': 0, 'keyword': 'SUCCESS', 'message': "调用成功" } FAIL_RES = { 'resCode': 500, 'resTime': 0, 'keyword': 'FAILED', 'message': "调用失败" } def print_err_result(e): FAIL_RES['error'] = e print(json.dumps(FAIL_RES, ensure_ascii=False)) exit(1) def _requests(full_url, params='{}'): try: # 处理null参数的情况 if params is None or params.lower() == 'null': params = '{}' # 解析参数 param = params.replace("'", '"') pars = json.loads(param) # 获取请求数据,默认为空字典 data = pars.get('data', {}) # 添加协议前缀(如果不存在) if not full_url.startswith(('http://', 'https://')): full_url = 'https://' + full_url # 解析URL以验证格式 parsed_url = urlparse(full_url) if not parsed_url.netloc: raise ValueError("无效的URL格式,缺少域名部分") # 确保路径以/开头 if not parsed_url.path.startswith('/'): full_url = urljoin(full_url, '/') isSuccess = True start = time.time() try: # 获取token和session token, sess = get_credentials() if token is None or sess is None: raise ValueError("无法获取有效的token或session") # 设置请求头,包括Cookie和Session headers = { 'Cookie': f'prod-token={token}', 'Content-Type': 'application/json' } # 发送POST请求(忽略SSL验证) res = requests.get(url=full_url, json=data, headers=headers, verify=False) # 新增解压解码处理过程 processor = HttpResponseProcessor(full_url, headers=res.headers) processor.response = res processor.raw_content = res.content processor.status_code = res.status_code try: # 解码内容 text_content = processor.decode_content() # 如果内容是JSON,可以解析为字典 try: json_content = json.loads(text_content) except json.JSONDecodeError: pass except Exception as e: raise e except requests.exceptions.SSLError as e: message = 'SSL证书验证失败' FAIL_RES['message'].append(message) print_err_result(str(e)) except Exception as e: message = '调用出现异常' FAIL_RES['message'].append(message) print_err_result(str(e)) # 计算耗时 res_time = (time.time() - start) * 1000 # 解析响应 try: response_data = res.json() statusCode = response_data.get('statusCode', res.status_code) except ValueError: statusCode = res.status_code # 判断请求是否成功 if 200 != res.status_code: isSuccess = False FAIL_RES['error'] = '调用网关拨测中间服务失败' message = 'resCode:' + str(res.status_code) FAIL_RES['message'].append(message) if 200 != statusCode: isSuccess = False FAIL_RES['error'] = '调用失败' try: message = 'resInfo:' + str(res.json().get('responseBody', 'No response body')) FAIL_RES['message'].append(message) except ValueError: message = 'resInfo: Invalid JSON response' FAIL_RES['message'].append(message) # 成功处理 SUC_RES['resTime'] = int(res_time) # 输出结果 if isSuccess: print(json.dumps(SUC_RES, ensure_ascii=False)) else: print(json.dumps(FAIL_RES, ensure_ascii=False)) except json.JSONDecodeError as e: print_err_result(f"JSON参数解析失败: {str(e)}") except ValueError as e: print_err_result(str(e)) except Exception as e: print_err_result(f"未知错误: {str(e)}") if __name__ == '__main__': args = sys.argv[1:] if len(args) < 1: raise Exception(''' 参数不足 用法: ./http_requests.py 完整URL [JSON参数] 示例: ./http_requests.py "https://api.example.com/endpoint" '{"data":{"key":"value"}}' ''') full_url = args[0] # 处理null参数的情况 params = args[1] if len(args) > 1 and args[1].lower() != 'null' else '{}' _requests(full_url, params) 我执行上面这段代码,未能运行成功,请根据异常信息改写代码,异常信息为:javax.script.ScriptException: org.python.antlr.ParseException: org.python.antlr.ParseException: encoding declaration in Unicode string at org.python.jsr223.PyScriptEngine.scriptException(PyScriptEngine.java:226) at org.python.jsr223.PyScriptEngine.compileScript(PyScriptEngine.java:93) at org.python.jsr223.PyScriptEngine.eval(PyScriptEngine.java:31) at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:233) at org.apache.jmeter.util.JSR223TestElement.processFileOrScript(JSR223TestElement.java:219) at org.apache.jmeter.modifiers.UTPJSR223PreProcessor.process(UTPJSR223PreProcessor.java:109) at org.apache.jmeter.threads.JMeterThread.runPreProcessors(JMeterThread.java:965) at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:549) at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:489) at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:256) at java.lang.Thread.run(Thread.java:748) Caused by: org.python.antlr.ParseException: encoding declaration in Unicode string at org.python.core.ParserFacade.prepBufReader(ParserFacade.java:281) at org.python.core.ParserFacade.parseExpressionOrModule(ParserFacade.java:123) at org.python.util.PythonInterpreter.compile(PythonInterpreter.java:321) at org.python.util.PythonInterpreter.compile(PythonInterpreter.java:317) at org.python.util.PythonInterpreter.compile(PythonInterpreter.java:309) at org.python.jsr223.PyScriptEngine.compileScript(PyScriptEngine.java:87) at org.python.jsr223.PyScriptEngine.eval(PyScriptEngine.java:31) at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:233) at org.apache.jmeter.util.JSR223TestElement.processFileOrScript(JSR223TestElement.java:219) at org.apache.jmeter.modifiers.UTPJSR223PreProcessor.process(UTPJSR223PreProcessor.java:109) at org.apache.jmeter.threads.JMeterThread.runPreProcessors(JMeterThread.java:965) at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:549) at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:489) at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:256) at java.lang.Thread.run(Thread.java:748) org.python.antlr.ParseException: org.python.antlr.ParseException: encoding declaration in Unicode string at org.python.core.Py.JavaError(Py.java:547) at org.python.core.ParserFacade.parseExpressionOrModule(ParserFacade.java:129) at org.python.util.PythonInterpreter.compile(PythonInterpreter.java:321) at org.python.util.PythonInterpreter.compile(PythonInterpreter.java:317) at org.python.util.PythonInterpreter.compile(PythonInterpreter.java:309) at org.python.jsr223.PyScriptEngine.compileScript(PyScriptEngine.java:87) ... 9 more Caused by: org.python.antlr.ParseException: encoding declaration in Unicode string at org.python.core.ParserFacade.prepBufReader(ParserFacade.java:281) at org.python.core.ParserFacade.parseExpressionOrModule(ParserFacade.java:123) ... 13 more
08-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值