当我运行此代码时,它给出了错误xml说明---处理POST请求的问题:不支持的Content-Type text / xml。我想使用httpClient将xml发送到一个URL,这是一个Web服务URL
public class HTTPClientDemo {
public static void main(String[] args) {
try
{
String inputXML = "<Style>0206.ard</Style><BoardCode>I-175B</BoardCode><BoardDesc>I-175 B Kraft</BoardDesc><GrainDirection>Vertical</GrainDirection><Unit>mm</Unit><PrintSide>Inside</PrintSide><Length>100</Length><Width>70</Width><Depth>45</Depth>";
URL url = new URL( "http://egwinae002:4415/ws/wstest003" );
// URL url = new URL( "https://dzone.com/articles/using-java-post-block-xml-web" );
URLConnection con = url.openConnection();
// con.connect();
// specify that we will send output and accept input
con.setDoInput(true);
con.setDoOutput(true);
con.setConnectTimeout( 20000 ); // long timeout, but not infinite
con.setReadTimeout( 20000 );
con.setUseCaches (false);
con.setDefaultUseCaches (false);
// tell the web server what we are sending
con.setRequestProperty ( "Content-Type", "text/xml" );
OutputStreamWriter writer = new OutputStreamWriter( con.getOutputStream() );
writer.write( inputXML );
writer.flush();
writer.close();
// reading the response
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 );
}
答案 0 :(得分:0)
// Have done modification and added some lines in your code, hope it will work
URLConnection con = url.openConnection();
//Added this one to make your connection http
HttpURLConnection conn = (HttpURLConnection) con;
// con.connect();
// specify that we will send output and accept input
conn .setDoInput(true);
conn .setDoOutput(true);
conn .setRequestProperty("accept-charset", "UTF-8");
// tell the web server what we are sending
conn.setRequestProperty ( "Content-Type", "text/xml" );
// set data posting method
conn.setRequestMethod("POST");
// OutputStreamWriter writer = new OutputStreamWriter( conn.getOutputStream() );
PrintWriter writer = new PrintWriter(conn.getOutputStream());
writer.write( inputXML );
writer.close();
// reading the response
// InputStreamReader reader = new InputStreamReader( conn.getInputStream() );
BufferedInputStream reader = new BufferedInputStream(conn.getInputStream());