0

我想将请求 url 和请求正文作为 xml 输入,并将输出作为响应 xml 代码。

是否有任何代码片段。

虽然我在 Java 中有一个代码:

import java.net.*;    // import java packages.  
import java.io.*;
import java.net.URL;

public class POST {
public static void main(String[] args) {
try{
       URL url = new URL("");  // Http request
       URLConnection con = url.openConnection();
       con.setDoInput(true);
       con.setDoOutput(true);
       con.setConnectTimeout( 20000 );
       con.setReadTimeout( 20000 );
       con.setUseCaches (false);
       con.setDefaultUseCaches (false);
       con.setRequestProperty ( "Content-Type", "application/xml" );
       OutputStreamWriter writer = new OutputStreamWriter( con.getOutputStream());
       writer.write("xml request body");  // xml request body
       writer.flush();
       writer.close();
       InputStreamReader reader = new InputStreamReader( con.getInputStream() );
       StringBuilder buf = new StringBuilder();
       char[] cbuf = new char[ 2048 ];
       int num;
       while ( -1 != (num=reader.read( cbuf )))
       {
              buf.append( cbuf, 0, num );
       }
       String result = buf.toString();
       System.err.println( "\nResponse from server after POST:\n" + result );
       }
catch( Throwable t )
{
       t.printStackTrace( System.out );
}
}
}
4

1 回答 1

1

你可以这样做:

import urllib2
req = urllib2.Request(url='http://example.com/yourpath/yourscript.extension', 
                  data='xml request body', 
                  headers={'Content-Type': 'application/xml'})
response = urllib2.urlopen(req)
xml = response.read()

对于 Python 3,您可以这样做:

import urllib.request
req = urllib.request.Request(url='http://example.com/yourpath/yourscript.extension',
                   data='xml request body')
req.add_header('Content-Type', 'application/xml')
response = urllib.request.urlopen(req)
xml = response.read())
于 2013-04-17T11:45:34.803 回答