使用Python模块发出POST请求

时间:2015-02-10 20:24:38

标签: java python json

我正在尝试访问正在开发的Web服务并通过Python脚本执行POST请求。我用Postman测试了url和参数,它运行正常。

我的剧本:

import requests
import json
import jsonpickle



f = open('C:\Users\Administrator\Desktop\myla311.json', 'r')



data = jsonpickle.encode(f)

url = "url"
headers = {'Content-type': 'raw', 'Accept': '/'}

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

print response.text


print response

我的输出:

C:\Python27\ArcGIS10.2\python.exe C:/Python27/ArcGIS10.2/websocket-client-0.23.0/websocket-client-0.23.0/examples/MYLAJSONtesting.py
com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class com.kahuna.request.wrapper.ServiceRequestWrapper] from String value ('null'); no single-String constructor/factory method
 at [Source: org.apache.camel.converter.stream.InputStreamCache@264330f4; line: 1, column: 1]
  at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164)
  at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:757)
  at com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:277)
  at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:289)
  at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1137)
  at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:139)
  at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:126)
  at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3051)
  at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2192)
  at org.apache.camel.component.jackson.JacksonDataFormat.unmarshal(JacksonDataFormat.java:128)
  at org.apache.camel.processor.UnmarshalProcessor.process(UnmarshalProcessor.java:67)
  at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:72)
  at org.apache.camel.processor.interceptor.TraceInterceptor.process(TraceInterceptor.java:163)
  at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
  at org.apache.camel.processor.Pipeline.process(Pipeline.java:118)
  at org.apache.camel.processor.Pipeline.process(Pipeline.java:80)
  at org.apache.camel.processor.TryProcessor.process(TryProcessor.java:111)
  at org.apache.camel.processor.TryProcessor.process(TryProcessor.java:82)
  at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:72)
  at org.apache.camel.processor.interceptor.TraceInterceptor.process(TraceInterceptor.java:163)
  at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
  at org.apache.camel.processor.Pipeline.process(Pipeline.java:118)
  at org.apache.camel.processor.Pipeline.process(Pipeline.java:80)
  at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
  at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:105)
  at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:87)
  at org.apache.camel.component.restlet.RestletConsumer$1.handle(RestletConsumer.java:55)
  at org.apache.camel.component.restlet.MethodBasedRouter.handle(MethodBasedRouter.java:54)
  at org.restlet.routing.Filter.doHandle(Filter.java:159)
  at org.restlet.routing.Filter.handle(Filter.java:206)
  at org.restlet.routing.Router.doHandle(Router.java:431)
  at org.restlet.routing.Router.handle(Router.java:648)
  at org.restlet.routing.Filter.doHandle(Filter.java:159)
  at org.restlet.routing.Filter.handle(Filter.java:206)
  at org.restlet.routing.Router.doHandle(Router.java:431)
  at org.restlet.routing.Router.handle(Router.java:648)
  at org.restlet.routing.Filter.doHandle(Filter.java:159)
  at org.restlet.engine.application.StatusFilter.doHandle(StatusFilter.java:155)
  at org.restlet.routing.Filter.handle(Filter.java:206)
  at org.restlet.routing.Filter.doHandle(Filter.java:159)
  at org.restlet.routing.Filter.handle(Filter.java:206)
  at org.restlet.engine.CompositeHelper.handle(CompositeHelper.java:211)
  at org.restlet.Component.handle(Component.java:406)
  at org.restlet.Server.handle(Server.java:516)
  at org.restlet.engine.connector.ServerHelper.handle(ServerHelper.java:72)
  at org.restlet.engine.adapter.HttpServerHelper.handle(HttpServerHelper.java:152)
  at org.restlet.ext.servlet.ServerServlet.service(ServerServlet.java:1118)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
  at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
  at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
  at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:301)
  at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
  at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:60)
  at oracle.security.jps.ee.http.JpsAbsFilter$1.run(JpsAbsFilter.java:119)
  at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:324)
  at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:460)
  at oracle.security.jps.ee.http.JpsAbsFilter.runJaasMode(JpsAbsFilter.java:103)
  at oracle.security.jps.ee.http.JpsAbsFilter.doFilter(JpsAbsFilter.java:171)
  at oracle.security.jps.ee.http.JpsFilter.doFilter(JpsFilter.java:71)
  at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:60)
  at oracle.security.wls.filter.SSOSessionSynchronizationFilter.doFilter(SSOSessionSynchronizationFilter.java:292)
  at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:60)
  at oracle.dms.servlet.DMSServletFilter.doFilter(DMSServletFilter.java:163)
  at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:60)
  at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3748)
  at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3714)
  at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
  at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
  at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2283)
  at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2182)
  at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1491)
  at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
  at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
<Response [500]>**

JSON文件:

{
    "MetaData": {},
    "RequestSpecificDetail": {
        "ParentSRNumberForLink": ""
    },
    "SRData": {
        "Anonymous": "Y",
        "Assignee": "",
        "CreatedByUserLogin": "",
        "CustomerAccessNumber": "",
        "LADWPAccountNo": "",
        "Language": "English",
        "ListOfLa311GisLayer": {},
        "ListOfLa311ServiceRequestNotes": {
            "La311ServiceRequestNotes": [
                {
                    "Comment": "hxhdudi",
                    "CommentType": "Feedback",
                    "FeedbackSRType": "Weed Abatement for Pvt Parcels",
                    "IsSrNoAvailable": "N"
                },
                {
                    "Comment": "",
                    "CommentType": "External",
                    "CreatedByUser": "",
                    "IsSrNoAvailable": "N"
                }
            ]
        },
        "LoginUser": "",
        "MobilOS": "Android",
        "NewContactEmail": "",
        "NewContactFirstName": "",
        "NewContactLastName": "",
        "NewContactPhone": "",
        "Owner": "Other",
        "ParentSRNumber": "",
        "Priority": "Normal",
        "SRCommunityPoliceStation": "RAMPART",
        "SRType": "Feedback",
        "ServiceDate": "01/22/2015",
        "Source": "Mobile App",
        "Status": "Open",
        "UpdatedByUserLogin": ""
    }
}

预期输出:

{"status":{"code":311,"message":"Service Request Successfully Submited","cause":""},"Response":{"PrimaryRowId":"1-3GZFZ","ListOfServiceRequest":{"ServiceRequest":[{"SRNumber":"1-5831279"}]}}}

enter image description here

编辑:更改json=data to data= data后收到

{"status":{"code":1007,"message":"Service Request Does Not Submitted.","cause":"java.lang.NullPointerException"}}
<Response [200]>

Process finished with exit code 0

2 个答案:

答案 0 :(得分:1)

data = jsonpickle.encode(f) doc表示您必须将Python对象传递给此函数。我不确定,也许这可能会有所帮助;
data = jsonpickle.encode( jsonpickle.decode(f.read()) ) 在这里,我尝试将json字符串转换为Python对象并返回到json。您可以尝试传递data = f.read()

答案 1 :(得分:0)

您正在使用Restlet库访问使用Java编写的Web服务。我认为Ryan O&#39; Donnell关于您对requests.post调用的使用以及对内容类型的需求是正确的。

请参阅requests documentation中的以下示例:

import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

你应该添加一个接受标题:

'Accept': 'application/json'

最后,不是在文件上使用openclose,而是使用with块更干净,更安全。您的代码可能如下所示:

with open('C:\Users\Administrator\Desktop\myla311.json', 'r') as f:
    payload = f.read()

headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
r = requests.post(url, data=payload, headers=headers)

我不确定您对jsonpickle的使用情况,但不需要对有效负载进行解码和重新编码。它已经是JSON,而且你想要发送它。