Java调用JavaWebService

1.pom配置

        
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>fluent-hc</artifactId>
            <version>4.5.5</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.9</version>
        </dependency>

2.http请求代码

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.nio.charset.Charset;

/**
 * HttpClient-invoke-WebService.
 * 
 * @author liwenxue
 */
public class HttpUtil {

    static int SOCKET_TIME_OUT = 30000;

    static int CONNECT_TIME_OUT = 30000;

    static final Log LOGGER = LogFactory.getLog(HttpUtil.class);

    public static String doPostSoap(String postUrl, String soapXml,String soapAction) {
        String retStr = "";
        try 
        {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    
            CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
            HttpPost httpPost = new HttpPost(postUrl);
    
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(SOCKET_TIME_OUT)
                    .setConnectTimeout(CONNECT_TIME_OUT).build();
            httpPost.setConfig(requestConfig);
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
            httpPost.setHeader("SOAPAction", soapAction);
            
            StringEntity data = new StringEntity(soapXml, Charset.forName("UTF-8"));
            httpPost.setEntity(data);
            CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            
            if (httpEntity != null) {
                retStr = EntityUtils.toString(httpEntity, "UTF-8");
                LOGGER.info("登录请求正常返回.");
            }
            else{
                LOGGER.info("登录请求未正常返回.");
            }
            closeableHttpClient.close();
        } catch (Exception e) {
            LOGGER.error("登录发生异常", e);
        }
        return retStr;
    }

}

3.调用示例

String authUrl="WebService地址";
String xml="WebService请求报文";
String itName="接口名";
String result = HttpUtil.doPostSoap(authUrl, xml,itName);

 

posted @ 2018-06-05 16:53  李文学  阅读(196)  评论(0编辑  收藏  举报