2014-03-25 233 views
1

我正在編寫一個使用Apache httpclient來調用SOAP web服務的Java代碼。到目前爲止,我已經寫下了一段工作正常的代碼。使用apache http客戶端向SOAP web服務發送請求

void post(String strURL, String strSoapAction, String strXMLFilename) throws Exception{ 

     File input = new File(strXMLFilename); 
     PostMethod post = new PostMethod(strURL); 
     RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); 
     post.setRequestEntity(entity); 
     post.setRequestHeader("SOAPAction", strSoapAction); 
     HttpClient httpclient = new HttpClient(); 
     try { 
      int result = httpclient.executeMethod(post); 
      System.out.println("Response status code: " + result); 
      System.out.println("Response body: "); 
      System.out.println(post.getResponseBodyAsString()); 
     } finally { 
      post.releaseConnection(); 
     } 
    } 

這裏,strXMLFilename是從SOAP UI採取SOAP請求文件(我複製SOAP UI請求XML,並將其粘貼在一些新的XML文件,並然後使用它)。 上面測試了一個將String作爲參數的服務。

但現在我的問題是它將能夠測試一個將File作爲輸入的服務嗎?我需要發送一個文件到服務中。在SOAP UI中,我能夠附加文件並測試服務,但無法對上面的代碼執行相同的操作。

請幫忙。

回答

0

好哥們,試試這個,它的工作對我罰款

void sendRequest()throws Exception { 
    System.out.println("Start sending " + action + " request"); 
    URL url = new URL(serviceURL); 
    HttpURLConnection rc = (HttpURLConnection)url.openConnection(); 
    //System.out.println("Connection opened " + rc); 
    rc.setRequestMethod("POST"); 
    rc.setDoOutput(true); 
    rc.setDoInput(true); 
    rc.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); 
    String reqStr = reqT.getRequest(); 
    int len = reqStr.length(); 
    rc.setRequestProperty("Content-Length", Integer.toString(len)); 
    rc.setRequestProperty("SOAPAction", soapActions[actionLookup(action)]); 
    rc.connect();  
    OutputStreamWriter out = new OutputStreamWriter(rc.getOutputStream()); 
    out.write(reqStr, 0, len); 
    out.flush(); 
    System.out.println("Request sent, reading response "); 
    InputStreamReader read = new InputStreamReader(rc.getInputStream()); 
    StringBuilder sb = new StringBuilder();  
    int ch = read.read(); 
    while(ch != -1){ 
     sb.append((char)ch); 
     ch = read.read(); 
    } 
    response = sb.toString(); 
    read.close(); 
    rc.disconnect(); 
    }  
+0

什麼是對其中調用getRequest調用「REQT」對象? – Anand

相關問題