2015-02-10 195 views
0

我試圖訪問正在開發中的Web服務並通過Python腳本執行POST請求。我用Postman測試了URL和參數,它工作正常。使用Python模塊POST請求

我的腳本:

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: [email protected]; 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 
+0

請發佈完整的異常文本,帶有回溯和源代碼行。 – 2015-02-10 20:27:01

+0

你是否正在運行Jython?這看起來像一個Java異常,而不是一個Python異常。 – 2015-02-10 20:27:29

+0

[斜視]那是什麼,一張螞蟻的圖片? – 2015-02-10 20:27:35

回答

1

data = jsonpickle.encode(f)doc說,你要通過Python對象到此功能。我不確定,也許這可能有幫助;
data = jsonpickle.encode(jsonpickle.decode(f.read())) 在這裏,我試圖將json字符串轉換爲Python對象並返回到json。你可以嘗試通過data = f.read()

+0

這工作;非常感謝Nizam。 – 2015-02-10 21:04:07

0

您正在訪問使用Restlet庫以Java編寫的Web服務。我認爲Ryan O'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) 

我不知道你的的​​使用是幹什麼的,但沒有必要解碼和重新編碼的有效載荷。它已經是JSON,這就是你想要發送的。

+0

jsonpickle序列化光盤上的json文件。 – 2015-02-10 21:08:43

+0

哎呀,糾正了我的答案 - 你已經閱讀json作爲一個字符串,所以不需要解碼或重新編碼它。 – cbare 2015-02-10 22:20:18