[英]Python Requests: POST JSON and file (multiform data) in 1 single request
從客戶端(使用python),我想使用multiform-data作為單個請求的一部分發送json數據和文件,但無法實現這一點。 在服務器端,我有Jersey,如果我使用curl發送請求,則工作正常,但如果使用Python發送相同的請求,則它不會起作用,因為Jersey崩潰。
python-requests軟件包版本0.8.2-1。 我無法升級到最新版本,因為這是ubuntu 12.04可用的最新版本。
低於curl的請求工作正常,服務器可以使用curl以下的請求成功處理請求。
curl -v -k -u "test:" -F file=@/tmp/test_new.zip --form upload_info='{"id": "1234", "test": "testing"}' -X POST "https://IP/test_api"
服務器端代碼段
@POST
@Path("/test_api")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response testAPIHandler(
@HeaderParam("Authorization") String auth,
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail,
@FormDataParam("upload_info") JSONObject jsonData) throws IOException {
try {
id = jsonData.getString("id");
url = jsonData.getString("test");
}
這是此python代碼,但不起作用。 甚至嘗試以相同的鍵名“ upload_info”將upload_info作為嵌套json發送,也無法正常工作。
def test_upload():
url = "https://IP/api/test_api"
user = "test"
passwd = None
upload_info = {'id': '1234', 'test': "testing"}
filepath = "/tmp/test_new.zip"
json_data = simplejson.dumps(upload_info)
fileobj = open(filepath, 'rb')
files = {'file' : ('test_new.zip', fileobj)}
headers = {'Content-type': 'multipart/form-data'}
r = requests.post(url, files=files, data=json_data, auth=(user, passwd), headers=headers)
print r.status_code
test_upload()
當我使用Python發送請求時,服務器端出現此異常
May 25, 2015 9:35:03 PM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.NullPointerException
at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.unquoteMediaTypeParameters(MultiPartReaderClientSide.java:227)
at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readMultiPart(MultiPartReaderClientSide.java:154)
at com.sun.jersey.multipart.impl.MultiPartReaderServerSide.readMultiPart(MultiPartReaderServerSide.java:80)
at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:144)
at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:82)
at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:488)
at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:552)
at com.sun.jersey.multipart.impl.FormDataMultiPartDispatchProvider$FormDataInjectableValuesProvider.getInjectableValues(FormDataMultiPartDispatchProvider.java:122)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1511)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1442)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1391)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1381)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:716)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:200)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
發送文件和數據參數作為request.post()的一部分對我不起作用,所以我最終要做的是將json數據作為輸入流發送。 我在Python端將JSON數據轉換為StringIO,然后在“文件”參數中將StringIO對象作為另一個文件對象發送,在服務器端,我將其作為InputStream接收,並轉換為JSONObject以獲取所需的值。
服務器上的Jersey代碼:
@POST
@Path("/test_upload_files")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response testHandler(
@HeaderParam("Authorization") String auth,
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail,
@FormDataParam("json_data") InputStream jsonStream) throws IOException {
String encoding = "UTF-8";
JSONObject jsonObject;
StringWriter writer = new StringWriter();
IOUtils.copy(jsonStream, writer, encoding);
String input = writer.toString();
try {
jsonObject = new JSONObject(input);
id = jsonObject.getString("id");
country = jsonObject.getString("country");
} catch (JSONException e) {
return null;
}
}
這是要發送的Python代碼:
import simplejson
import requests
from cStringIO import StringIO
def upload_files_and_json():
url = "https://IP/test_upload_files"
user = "foo"
passwd = None
upload_info = {'id': '1234', 'country': 'zzz'}
filepath = "/tmp/test.zip"
json_data = simplejson.dumps(upload_info)
json_input = StringIO(json_data)
fileobj = open(filepath, 'rb')
files = {'file' : ('test.zip', fileobj), 'json_data': json_input}
r = requests.post(url, files=files, auth=(user, passwd))
這是我嘗試安裝請求包的方法
import requests
class RestCall:
if __name__ == '__main__':
url = "http://url.com/rest/doj/webservice/helloge"
data = dict(fn='Test', ln='Me')
r = requests.post(url, data=data, allow_redirects=True)
print (r.content)
您的服務器組件如下所示
@POST
@Path("/helloge")
@Produces("text/plain")
public String helloGe(@FormParam("fn") String fn,@FormParam("ln") String ln){
return "Hello "+fn+" "+ln;
}
您的輸出是:
b'Hello Test Me'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.