基于HttpClient的WebService调用

WebService的调用有很多种方式,本地调用(静态调用),远程调用(动态)

关于上边静态,动态是我个人的理解,没有权威性,个人喜好而已

本地调用

具体操作请看:http://www.jianshu.com/p/1e9582a4b340

远程调用

远程调用的方式比较多,例如利用cxf,axis、axis2 、HttpClient等框架的调用,这里具体看基于HttpClient的调用, HttpClient 3和4 使用方式稍有区别,经测试,4.5.2版本不支持jdk1.5

  • HttpClient 3.x
public static String doPostSOAP_RemoveUser(String logonName){
        Properties prop = new Properties(); 
        PostMethod post = null;
        String responseXml = null;
        String json= null;
        try {
        InputStream in = HttpClient3_0_SOAPUtil.class.getResourceAsStream("/sysPath.properties");
        prop.load(in);
        String postURL = prop.getProperty("postURL");
        post = new PostMethod(postURL);
        post.setRequestHeader("Content-Type","text/xml;charset=utf-8");
            //File input = new File(strXMLFilename);
            // Prepare HTTP post
            // Request content will be retrieved directly
            // from the input stream
                String systemId = prop.getProperty("systemId");                      
                String strWSDLXml_RemoveUser = "<?xml version = \"1.0\" ?>" 
                        + "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:tem=\"http://tempuri.org/\">"
                        + "   <soap:Header/>"
                        + "   <soap:Body>"
                        + "      <tem:RemoveUser>"
                        + "         <!--Optional:-->"
                        + "         <tem:systemId>"+systemId+"</tem:systemId>"
                        + "         <!--Optional:-->"
                        + "         <tem:logonName>"+logonName+"</tem:logonName>"
                        + "      </tem:RemoveUser>"
                        + "   </soap:Body>"
                        + "</soap:Envelope>";
                System.out.println(strWSDLXml_RemoveUser);
                String strSoapAction_RemoveUser = prop.getProperty("strSoapAction_RemoveUser");
            byte[] b = strWSDLXml_RemoveUser.getBytes("utf-8");
            InputStream is = new ByteArrayInputStream(b,0,b.length);
            RequestEntity entity = new InputStreamRequestEntity(is,b.length,"application/soap+xml; charset=utf-8");
            post.setRequestEntity(entity);
            // consult documentation for your web service
            post.setRequestHeader("SOAPAction", strSoapAction_RemoveUser);
            // Get HTTP client
            HttpClient httpclient = new HttpClient();
            // Execute request
            int result = httpclient.executeMethod(post);
            // Display status code
            //System.out.println("Response status code: " + result);
            // Display response
            //System.out.println("Response body: ");
            responseXml = post.getResponseBodyAsString();
            //System.out.println(responseXml);
            Document document_ret = DocumentHelper.parseText(responseXml);
            json = document_ret.getRootElement().element("Body").element("RemoveUserResponse").element("RemoveUserResult").getText();
            
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Release current connection to the connection pool once you are done
            post.releaseConnection();
        }
        return json;
    }

这是我个人根据相应业务而产生的代码,不同业务可根据业务需求做相应的改动,strWSDLXml_RemoveUser 这个字符串是在soapUI 中得到,

image.png

关于soapUI我也是小白,不多做解释,具体自行百度、google。
上述代码使用了到了外部配置文件


sysPath 内容如下

systemId=xxxxxxxxxxxxxxxxxxxx
postURL=http://xxx.xxx.xxx.xxx:9999/webservice/externalservice/userservice.asmx
strSoapAction_RemoveUser=http://xxxxxx.xxx/RemoveUse

jar 包依赖关系

image.png

调用上述方法,将会得到调用webService后的响应内容
下边给出3.x的官方提供的示例

import java.io.File;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.FileRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

/**
 *
 * This is a sample application that demonstrates
 * how to use the Jakarta HttpClient API.
 *
 * This application sends an XML document
 * to a remote web server using HTTP POST
 *
 * @author Sean C. Sullivan
 * @author Ortwin Glueck
 * @author Oleg Kalnichevski
 * @author Paul King
 */
public class PostSOAP {

    /**
     *
     * Usage:
     *          java PostSOAP http://mywebserver:80/ SOAPAction c:\foo.xml
     *
     *  @param args command line arguments
     *                 Argument 0 is a URL to a web server
     *                 Argument 1 is the SOAP Action
     *                 Argument 2 is a local filename
     *
     */
    public static void main(String[] args) throws Exception {
        if (args.length != 3) {
            System.out.println("Usage: java -classpath <classpath> [-Dorg.apache.commons.logging.simplelog.defaultlog=<loglevel>] PostSOAP <url> <soapaction> <filename>]");
            System.out.println("<classpath> - must contain the commons-httpclient.jar and commons-logging.jar");
            System.out.println("<loglevel> - one of error, warn, info, debug, trace");
            System.out.println("<url> - the URL to post the file to");
            System.out.println("<soapaction> - the SOAP action header value");
            System.out.println("<filename> - file to post to the URL");
            System.out.println();
            System.exit(1);
        }
        // Get target URL
        String strURL = args[0];
        // Get SOAP action
        String strSoapAction = args[1];
        // Get file to be posted
        String strXMLFilename = args[2];
        File input = new File(strXMLFilename);
        // Prepare HTTP post
        PostMethod post = new PostMethod(strURL);
        // Request content will be retrieved directly
        // from the input stream
        RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
        post.setRequestEntity(entity);
        // consult documentation for your web service
        post.setRequestHeader("SOAPAction", strSoapAction);
        // Get HTTP client
        HttpClient httpclient = new HttpClient();
        // Execute request
        try {
            int result = httpclient.executeMethod(post);
            // Display status code
            System.out.println("Response status code: " + result);
            // Display response
            System.out.println("Response body: ");
            System.out.println(post.getResponseBodyAsString());
        } finally {
            // Release current connection to the connection pool once you are done
            post.releaseConnection();
        }
    }
}

3.x 项目官方地址:http://hc.apache.org/httpclient-3.x/

jar包依赖


image.png
 public static String doPostSoap1_1(String postUrl, String soapXml,  
                String soapAction) {  
            String retStr = "";  
          
            // 创建HttpClientBuilder  
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();  
            // HttpClient  
            CloseableHttpClient closeableHttpClient = httpClientBuilder.build();  
            HttpPost httpPost = new HttpPost(postUrl);  
                    //  设置请求和传输超时时间  
            RequestConfig requestConfig = RequestConfig.custom()  
                    .setSocketTimeout(socketTimeout)  
                    .setConnectTimeout(connectTimeout).build();  
            httpPost.setConfig(requestConfig);  
            try { 
                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");  
                   System.out.println("response:" + retStr);  
                }  
                // 释放资源  
                closeableHttpClient.close();  
            } catch (Exception e) {  
               // logger.error("exception in doPostSoap1_1", e);  
                e.printStackTrace();
            }  
            return retStr;  
        }  
     public static void main(String[] args) {
                String systemId = "ssss";
                String jsonUserInfo="";
                String adduser = "<?xml version = \"1.0\" ?>" 
                        + "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">"
                        + "   <soapenv:Header/>"
                        + "   <soapenv:Body>"
                        + "      <tem:AddUser>"
                        + "         <!--Optional:-->"
                        + "         <tem:systemId>"+systemId+"</tem:systemId>"
                        + "         <!--Optional:-->"
                        + "         <tem:jsonUserInfo>"+jsonUserInfo+"</tem:jsonUserInfo>"
                        + "      </tem:AddUser>"
                        + "   </soapenv:Body>"
                        + "</soapenv:Envelope>";
                String postUrl = "http://1xxx.xxx.x.x:9999/webservice/externalservice/userservice.asmx"; 
                String repXml= doPostSoap1_1(postUrl, adduser, "http://tempuri.org/AddUser");                          
        }

之后解析repXml得到响应的json 字符串;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,099评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,473评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,229评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,570评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,427评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,335评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,737评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,392评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,693评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,730评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,512评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,349评论 3 314
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,750评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,017评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,290评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,706评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,904评论 2 335

推荐阅读更多精彩内容