使用apache http客户端向SOAP Web服务发送请求

时间:2014-03-25 10:50:29

标签: java web-services soap apache-commons-httpclient

我正在使用Apache httpclient编写Java代码来调用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中,我能够附加文件并测试服务,但不能对上面的代码执行相同的操作。

请帮忙。

1 个答案:

答案 0 :(得分: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();  
  }