【问题标题】:Exception "A JSONObject text must begin with '{' at character 0 of" when posting data using request()使用 request() 发布数据时出现异常“JSONObject 文本必须在字符 0 处以 '{' 开头”
【发布时间】:2017-01-06 07:04:37
【问题描述】:

我打算使用以下代码向服务器发送请求。我花了超过 1 天的时间来解决这个问题,但没有任何进展。请原谅我,因为公司安全政策,我不得不隐藏真实的 URL 地址。

import requests

get_ci = requests.session()

get_ci_url = 'https://this_is_a_fake_URL_to_paste_in_stackoverflow.JSON'
get_ci_param_dict = {"Username": "fake","Password": "fakefakefake","CIType": "system","CIID": "sampleid","CIName": "","AttrFilter": "","SubObjFilter": ""}
get_ci_param_str = str(get_ci_param_dict)

print(get_ci_param_dict)
print(get_ci_param_str)

get_ci_result = get_ci.request('POST', url=get_ci_url, params=get_ci_param_str, verify=False)

print(get_ci_result.status_code)
print(get_ci_result.text)

我在运行结果中得到的是,

C:\Python34\python.exe C:/Users/this/is/the/fake/path/Test_02.py
{'CIID': 'sampleid', 'CIType': 'system', 'AttrFilter': '', 'Password': 'fake', 'CIName': '', 'Username': 'fake', 'SubObjFilter': ''}
{'CIID': 'sampleid', 'CIType': 'system', 'AttrFilter': '', 'Password': 'fake', 'CIName': '', 'Username': 'fake', 'SubObjFilter': ''}
C:\Python34\lib\requests\packages\urllib3\connectionpool.py:843: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
500
<ns1:XMLFault xmlns:ns1="http://cxf.apache.org/bindings/xformat"><ns1:faultstring xmlns:ns1="http://cxf.apache.org/bindings/xformat">*org.codehaus.jettison.json.JSONException: A JSONObject text must begin with '{' at character 0 of* </ns1:faultstring></ns1:XMLFault>

Process finished with exit code 0

更多提示,

  1. 我已经联系了服务器代码开发人员 - 他们只需要一个 以“参数”方式发送的 JSON 格式的字符串。这意味着它 在request() 中使用params 是正确的。

  2. 我试过dumps.json(get_ci_param_dict) =>同样的结果。

  3. 当我只请求服务器的root时它返回了200代码, 这证明我的网址没问题。


将params 更新为data 时的附加日志。

C:\Python34\lib\requests\packages\urllib3\connectionpool.py:843: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
500
<html><head><title>Apache Tomcat/7.0.61 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 500 - 1</h1><HR size="1" noshade="noshade"><p><b>type</b> Exception report</p><p><b>message</b> <u>1</u></p><p><b>description</b> <u>The server encountered an internal error that prevented it from fulfilling this request.</u></p><p><b>exception</b> <pre>java.lang.ArrayIndexOutOfBoundsException: 1
    com.fake.security.XSSHttpReuquestWrapper.GeneralParameters(XSSHttpReuquestWrapper.java:158)
    com.fake.security.XSSHttpReuquestWrapper.checkParameter(XSSHttpReuquestWrapper.java:101)
    com.fake.security.XSSHttpReuquestWrapper.validateParameter(XSSHttpReuquestWrapper.java:142)
    com.fake.security.XSSSecurityFilter.doFilter(XSSSecurityFilter.java:35)
    com.fake.webservice.interceptor.GetContextFilter.doFilter(GetContextFilter.java:24)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
</pre></p><p><b>note</b> <u>The full stack trace of the root cause is available in the Apache Tomcat/7.0.61 logs.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.61</h3></body></html>

Process finished with exit code 0

此问题的最终解决方案

@e4c5 您的建议有助于找出最终解决方案。 param 应该通过data 发送到服务器,因为data 应该作为官方文档中定义的dict 或byte 发送,所以需要使用param 作为dict 键发送。请看下面的代码,

import requests
import json


get_ci_url = 'https://sample.fake.com:0000/sample/fake/fakeagain.JSON'
get_ci_param_dict = {"Username": "fake","Password": "fakefake".......}
get_ci_param_json = json.dumps(get_ci_param_dict)

params = {'param': get_ci_param_json}

get_ci_result = requests.request('POST', url=get_ci_url, data=params, verify=False)

print(get_ci_result.status_code)
print(get_ci_result.text)

根本原因:param 应该通过data 参数发送。官方文档已经明确指出 => :param data: (optional) 字典、字节或类似文件的对象在 :class:Request 的正文中发送。

感谢我的同事 - Mr.J 和 @e4c5 的大力帮助。

【问题讨论】:

    标签: python json post parameters python-requests


    【解决方案1】:

    如果你的服务器期望的是json,你应该使用json参数来python请求

    get_ci_result = get_ci.request('POST', url=get_ci_url,  
        json=get_ci_param_dict, verify=False)
    

    还要注意,params 参数通常与 get 一起使用(用于格式化 URL 的查询字符串),对于 post 和 form 数据,它应该是 data 和字典。

    更多信息请参考:http://docs.python-requests.org/en/master/api/

    【讨论】:

    • 非常感谢@e4c5 回答我关于 SO 的第一个问题。但是对于问题本身。 1)我之前尝试过同时使用'data'和'json',服务器返回另一个异常告诉我使用'json'时请求中需要'params',使用'data'时会遇到同样的错误。 2)这也与我的 TIP1 一致) - 以“参数”方式“以 JSON 格式发送字符串”,每个确认服务器端开发人员。 3) 实际上 POST 请求是从服务器获取数据,我在“参数”中发送的是使用 SOAPUI 时的查询。
    • 对不起,第一条评论应该被删除。当按下“Enter”按钮时,我试图开始第二行而不是发布评论。 :)
    • 不,你完全误解了 python-requests。在 params 中发送的内容不会显示为服务器的 POST 数据。您可以参考文档以自己确认这些事实
    • 我已经尝试过json 和data,但是遇到了我所说的参数丢失异常。我也试过GET方法被告知GET方法不被服务器支持。
    • 您需要了解parameter 是一个更广泛的术语。服务器没有引用您在请求中使用的param 参数。 json 是要使用的正确参数。这里的问题是您通过 json 字典向服务器发送了错误的 parameters。为此,您需要提出另一个问题或查看服务器预期的 参数。这里您的参数是用户名、fakefakefake 等
    【解决方案2】:

    发出请求时,您的数据字典将自动为form-encoded。当服务器接受 JSON 编码的 POST/PATCH 数据而不是 form-encoded 数据时,使用 json 参数。

    response = requests.post(url=url, headers=headers, json=data)
    

    在请求中使用 json 参数会将 header 中的 Content-Type 更改为 application/json。

    访问https://2.python-requests.org/en/master/user/quickstart/#More-complicated-POST-requests

    【讨论】:

      【解决方案3】:

      我也有类似的问题。

      即使我的数据已经是字典,我也需要再次 json.dumps(data):

      response = requests.post(url = url ,headers=head,data = json.dumps(data))
      


      我只是想分享一下,以防有人遇到类似问题。

      【讨论】:

        猜你喜欢
        • 2015-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多