2016-04-28 73 views
0

當我運行這段代碼時,它給了我錯誤的XML說明---問題處理POST請求:不支持的內容類型文本/ XML。我想用HttpClient的一個XML發送到它是一個網絡服務的網址我想發佈一個XML到另一臺服務器

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
// 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()); 
+0

抱歉,不工作的URL。 –

相關問題