1 package com.http.soap; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.nio.charset.Charset; 7 8 import org.apache.http.HttpEntity; 9 import org.apache.http.client.ClientProtocolException; 10 import org.apache.http.client.config.RequestConfig; 11 import org.apache.http.client.methods.CloseableHttpResponse; 12 import org.apache.http.client.methods.HttpPost; 13 import org.apache.http.entity.StringEntity; 14 import org.apache.http.impl.client.CloseableHttpClient; 15 import org.apache.http.impl.client.HttpClientBuilder; 16 import org.apache.http.util.EntityUtils; 17 18 public class HttpPostToSoap { 19 static int socketTimeout = 10000;// 請求超時時間 20 static int connectTimeout = 10000;// 傳輸超時時間 21 static final String soap = "text/xml;charset=UTF-8"; 22 static final String soap11 = "application/soap+xml;charset=UTF-8"; 23 24 /** 25 * 同步HttpPost請求發送SOAP格式的消息 26 * 27 * @param webServiceURL 28 * WebService接口地址 29 * @param soapXml 30 * 消息體 31 * @param soapAction 32 * soapAction 33 * @param soapType 34 * soap版本 35 * @return 36 */ 37 public static String doPostSoap(String webServiceURL, String soapXml,String soapAction, String soapType) { 38 // BufferedReader reader = null; 39 // 創建HttpClient 40 HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); 41 CloseableHttpClient closeableHttpClient = httpClientBuilder.build(); 42 // 創建Post請求 43 HttpPost httpPost = new HttpPost(webServiceURL); 44 // 設置請求和傳輸超時時間 45 RequestConfig requestConfig = RequestConfig.custom() 46 .setSocketTimeout(socketTimeout) 47 .setConnectTimeout(connectTimeout).build(); 48 httpPost.setConfig(requestConfig); 49 // 設置Post請求報文頭部 50 httpPost.setHeader("Content-Type", soapType); 51 httpPost.setHeader("SOAPAction", soapAction); 52 // 添加報文內容 53 StringEntity data = new StringEntity(soapXml, Charset.forName("UTF-8")); 54 httpPost.setEntity(data); 55 try { 56 // 執行請求獲取返回報文 57 CloseableHttpResponse response = closeableHttpClient.execute(httpPost); 58 HttpEntity httpEntity = response.getEntity(); 59 if (httpEntity != null) { 60 // 打印響應內容 61 return EntityUtils.toString(httpEntity, "UTF-8"); 62 } 63 // if (httpEntity != null) { 64 // reader = new BufferedReader(new InputStreamReader(httpEntity .getContent(), "UTF-8")); 65 // StringBuffer sb = new StringBuffer(); 66 // String line = null; 67 // while ((line = reader.readLine()) != null) { 68 // sb.append(line); 69 // sb.append("\r\n"); 70 // } 71 // return sb.toString(); 72 // } 73 // 釋放資源 74 closeableHttpClient.close(); 75 } catch (ClientProtocolException e) { 76 e.printStackTrace(); 77 } catch (IOException e) { 78 e.printStackTrace(); 79 } 80 return null; 81 } 82 }
測試
package com.http.soap; public class TestSoap { public static void main(String[] args) { String soapXml=“請求報文”; String result=HttpToSoap.doPostSoap("http://192.168.18.161:8080/mtosi", soapXml, "", HttpToSoap.soap); System.out.println(result); } }