2012-10-10 70 views
4

我想送一個XML文件作爲SOAP服務器的請求。 這裏是我的代碼:從服務器(從Sending HTTP Post request with SOAP action using org.apache.http修改)爲什麼這個簡單的SOAP客戶端無法正常工作(org.apache.http)?

import org.apache.http.client.*; 
import org.apache.http.client.methods.*; 
import org.apache.http.impl.client.*; 
import org.apache.http.entity.StringEntity; 
import org.apache.http.protocol.HTTP; 
import org.apache.http.HttpResponse; 
import java.net.URI; 

public static void req() { 
     try { 
      HttpClient httpclient = new DefaultHttpClient(); 
      String body="xml here"; 
      String bodyLength=new Integer(body.length()).toString(); 

      URI uri=new URI("http://1.1.1.1:100/Service"); 
      HttpPost httpPost = new HttpPost(uri); 
      httpPost.setHeader("SOAPAction", "MonitoringService"); 
      httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8"); 


      StringEntity entity = new StringEntity(body, "text/xml",HTTP.DEFAULT_CONTENT_CHARSET); 
      httpPost.setEntity(entity); 

      RequestWrapper requestWrapper=new RequestWrapper(httpPost); 
      requestWrapper.setMethod("POST"); 


      requestWrapper.setHeader("Content-Length",bodyLength); 
      HttpResponse response = httpclient.execute(requestWrapper); 
      System.out.println(response); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

在此之前,我得到錯誤「HTTP 500」(內部服務器錯誤),但我現在沒有得到任何答覆的。我知道服務器正常工作,因爲與其他客戶端沒有問題。

謝謝。

+0

*「before」*是什麼意思?如果你發送一個有效的xml字符串而不是'xml here'會發生什麼? – brimborium

+0

請指定您是否使用IDE,如果是,那麼哪個。如果您使用的是Oracle Jdeveloper 11g等IDE,則只需導入WSDL,IDE將自動生成代碼。 –

+0

您應該發佈請求的正文。如果你的xml有問題,你可能不會得到任何迴應。 – Err

回答

6

org.apache.http API不是SOAP/Web服務感知,所以你在做一個非標準的方式棘手的工作。該代碼是不是很Java友好的或柔性的,因爲它不能自動「綁定」(轉換)java對象數據到SOAP請求和流出SOAP響應的。這是一個有點冗長,棘手的調試和獲得工作,而脆 - 你處理的全SOAP協議,包括故障處理等?

我可以建議使用JAX-WS標準,這是內置到JVM:

1.保存WSDL文件到本地磁盤
例如<app path>/META-INF/wsdl/abc.com/calculator/Calculator.wsdl
如果沒有WSDL,您可以保存結果頁面輸入到瀏覽器&磁盤:
http://abc.com/calculator/Calculator?wsdl

2.使用的wsimport命令WSDL轉換成Java類文件
對於JDK,工具在<jdkdir>\bin\wsimport.exe (or .sh)
對於應用服務器,將會像<app_server_root>\bin\wsimport.exe (or .sh)

<filepath>\wsimport -keep -verbose <wsdlpath>\Calculator.wsdl

或者如果您的WSDL通過預先存在的web服務

<filepath>\wsimport -keep -verbose http://abc.com/calculator/Calculator?wsdl

可用(也可以包括「-p com.abc.calculator」來設置生成的類的封裝)

文件像生成以下 - 包括採取這些Ë源文件在你的Java項目:

com\abc\calculator\ObjectFactory.java  
com\abc\calculator\package-info.java  
com\abc\calculator\Calculator.java  ............................name = `<wsdl:portType>` name attribute  
com\abc\calculator\CalculatorService.java  ................name = `<wsdl:service>` name attribute  
com\abc\calculator\CalculatorRequestType.java .......name = schema type used in input message  
com\abc\calculator\CalculatorResultType.java ..........name = schema type used in output message 

2.創建一個JAX-WS SOAP Web服務客戶端

package com.abc.calculator.client; 

import javax.xml.ws.WebServiceRef; 
import com.abc.calculator.CalculatorService; 
import com.abc.calculator.Calculator; 

public class CalculatorClient { 

    @WebServiceRef(wsdlLocation="META-INF/wsdl/abc.com/calculator/Calculator.wsdl") 
    // or @WebServiceRef(wsdlLocation="http://abc.com/calculator/Calculator?wsdl") 
    public static CalculatorService calculatorService; 

    public CalculatorResponseType testCalculation() { 
     try { 
      CalculatorRequestType request = new CalculatorRequest(); 
      request.setSomeParameter("abc"); 
      request.setOtherParameter(3); 
      Calculator calculator = calculatorService.getCalculatorPort(); 
      // automatically generate SOAP XML message, send via HTTP, 
      // receive & marshal response to java object 
      String response = calculator.doCalculation(response); 
     } catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
2

嘗試發送這樣的請求。這是我做的最後一次:

try 
     { 
      StringBuffer strBuffer = new StringBuffer(); 
      HttpURLConnection connection = connectToEndPoint(endpoint); 
      OutputStream outputStream = generateXMLOutput(connection, yourvalue, strDate); 

      InputStream inputStream = connection.getInputStream(); 

      int i; 
      while ((i = inputStream.read()) != -1) { 
       Writer writer = new StringWriter(); 
       writer.write(i); 
       strBuffer.append(writer.toString()); 

      String status = xmlOutputParse(strBuffer); 

和所使用的功能:

private static HttpURLConnection connectToEndPoint(String wsEndPoint) throws MalformedURLException, IOException { 
    URL urlEndPoint = new URL(wsEndPoint); 
    URLConnection urlEndPointConnection = urlEndPoint.openConnection(); 
    HttpURLConnection httpUrlconnection = (HttpURLConnection) urlEndPointConnection; 
    httpUrlconnection.setDoOutput(true); 
    httpUrlconnection.setDoInput(true); 
    httpUrlconnection.setRequestMethod("POST"); 
    httpUrlconnection.setRequestProperty("content-type", "application/soap+xml;charset=UTF-8"); 
    // set connection time out to 2 seconds 
    System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(2 * 1000)); 
    // httpUrlconnection.setConnectTimeout(2*1000); 
    // set input stream read timeout to 2 seconds 
    System.setProperty("sun.net.client.defaultReadTimeout", String.valueOf(2 * 1000)); 
    // httpUrlconnection.setReadTimeout(2*1000); 
    return httpUrlconnection; 
} 

如果您手動創建XML(修改您的需要):

private static OutputStream generateXMLOutput(HttpURLConnection conn, String msisdn, String strDate) throws IOException { 
    OutputStream outputStream = conn.getOutputStream(); 

    StringBuffer buf = new StringBuffer(); 

    buf.append("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:ins=\"http://yournamespace">\r\n"); 
    buf.append("<soap:Header xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">\r\n"); 

    //..... append all your lines .......  

    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8"); 

    outputStreamWriter.write("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:ins=\"http://yournamespace\">\r\n"); 
    outputStreamWriter.write("<soap:Header xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">\r\n"); 
    //..... write all your lines .......  

    outputStreamWriter.flush(); 

    outputStream.close(); 
    return outputStream; 
} 

而函數返回您的WS答案:

private static String xmlOutputParse(StringBuffer xmlInputParam) throws IOException, ParserConfigurationException, SAXException { 
    String status = null; 
    DocumentBuilderFactory docBuilderfFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder documentBuilder = docBuilderfFactory.newDocumentBuilder(); 
    InputSource inputSource = new InputSource(); 
    inputSource.setCharacterStream(new StringReader(xmlInputParam.toString())); 
    Document document = documentBuilder.parse(inputSource); 
    NodeList nodeList = document.getElementsByTagName("ResponseHeader"); 
    Element element = (Element) nodeList.item(0); 
    if (element == null) { 
     return null; 
    } 
    NodeList name = element.getElementsByTagName("Status"); 
    Element line = (Element) name.item(0); 
    if (line == null) { 
     return null; 
    } 
    if (line.getFirstChild() instanceof CharacterData) { 
     CharacterData cd = (CharacterData) line.getFirstChild(); 
     status = cd.getData().trim(); 
    } 
    return status; 
} 

我認爲這個解決方案(儘管很長)適用於大多數情況。我希望你能適應你的需求。

此致敬禮!

相關問題