![](/img/trans.png)
[英]Sending HTTP Post request with SOAP action using org.apache.http
[英]Sending request to SOAP web service using Apache http client
我正在使用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 中,我能夠附加文件並測試服務,但無法對上述代碼進行相同的操作。
好的,伙計,試試這個,對我來說很好用
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.