首先下載HttpClient 4.3.1的jar包,下載地址:http://mirrors.hust.edu.cn/apache//httpcomponents/httpclient/binary/httpcomponents-client-4.3.1-bin.zip。 java
依賴Jar包文件:commons-codec-1.6.jar,httpclient-4.3.1.jar,httpcore-4.3.jar,另外,須要額外加入log4j-1.2.16.jar及commons-logging-1.1.3.jar包。 apache
示例代碼以下: app
package com.project.ws; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class WSClient { public static final String WSDLURL = "http://127.0.0.1:8080/Test.asmx?wsdl"; public static void main(String[] args){ HttpClient client = HttpClients.createDefault(); String reqSoapData = buildReqSoapData(); HttpPost post = new HttpPost(WSDLURL); try { HttpEntity re = new StringEntity(reqSoapData,"UTF-8"); post.setHeader("Content-Type","application/soap+xml; charset=UTF-8"); //post.setHeader("Content-Length", String.valueOf(reqSoapData.length())); post.setEntity(re); HttpResponse response = client.execute(post); System.out.println("請求服務的Soap文本:"+EntityUtils.toString(post.getEntity())); System.out.println("請求服務結果狀態:"+response.getStatusLine()); System.out.println("請求服務返回XML文本:"+EntityUtils.toString(response.getEntity())); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 生成請求服務的Soap XML字符串 * @return String */ public static String buildReqSoapData(){ String soapData = ""; soapData += "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">" + "<soap12:Body>" + " <getStudentInfo xmlns=\"http://tempuri.org/\">" + " <strKey>person</strKey>" + " <strwhere>name='花無影'</strwhere>" + "</getStudentInfo>" + " </soap12:Body>" + "</soap12:Envelope>" ; return soapData; } }
說明:其中生成請求的Soap文本中, post
<getStudentInfo xmlns="http://tempuri.org/"> ui
<strKey>person</strKey> code
<strwhere>name='花無影'</strwhere> component
</getStudentInfo>, xml
getStudentInfo爲方法名稱,strKey及strwhere爲參數名稱,對應的值爲參數的值。 ip