httpclient发送webservice请求

先说下项目背景,公司项目需要通过webservice进行数据交互,拿到目标接口后,想研究下使用http请求发送webservice请求。

其中涉及到的技术点就是,http,xml解析。

下面就是代码部分了。

DefaultHttpClient httpClient = null;
Map map = new HashMap();
try {
    httpClient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("xxx.xxx.xxx"); //webservice服务地址
    String soapRequestData = ‘需要发送的xml’; //soap协议的格式,定义了方法和参数
    HttpEntity re = new StringEntity(soapRequestData, HTTP.UTF_8);
    httppost.setHeader("Content-Type","application/soap+xml; charset=utf-8");
    httppost.setEntity(re);
    HttpResponse response = httpClient.execute(httppost); //调用接口
    System.out.println(response.getStatusLine().getStatusCode());
    if(response.getStatusLine().getStatusCode() == 200) {  //调用状态
        String xmlString = EntityUtils.toString(response.getEntity());
        String statusString = parseXMLSTRING(xmlString,"status");  //解析接口返回的值
        String messageString = parseXMLSTRING(xmlString,"message");  //解析接口返回的值
        map.put("status",statusString);
        map.put("message",messageString);
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    httpClient.getConnectionManager().shutdown(); //关闭连接
}
return map;
 
  //xml文件的解析
    public  static String parseXMLSTRING(String xmlString,String nodeName){
        String returnJson = "";
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(xmlString)));
            Element root = doc.getDocumentElement();//根节点

            //根据标签名称获取该名称的所有节点对象
            NodeList nodelist = doc.getElementsByTagName(nodeName);
            //遍历
            for (int i = 0; i < nodelist.getLength(); i++) {
                //得到具体的某个节点对象
                Node node = nodelist.item(i);
                result=node.getFirstChild().getNodeValue();
//                System.out.println(returnJson);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
各位小友可根据自己项目需求进行封装,即可使用,亲测可用。




你可能感兴趣的:(探索springboot,httpclient,webservice,post,xml)