htppClient调用webservice,并解析返回的xml字符串

参考:https://blog.csdn.net/yapengliu/article/details/86596096?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase

引入依赖:

<!-- http -->
<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.5.3</version>
</dependency>

 
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.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.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
 
public class HttpClientDemo {
 
    /**
     * 接口调用
     * 
     * @param url 接口地址 json 为参数 参考(gson.getInstance.toJson(new
     *            HashMap("参数名","参数值")))需要转换  * 成json串格式的
     */
    public static String doClient(String url, String json) {
        return doPost(url, json);
 
    }
 
    /**
     * 获取连接
     * 
     * @return CloseableHttpClient对象
     */
    public static CloseableHttpClient buildHttpClient() {
        CloseableHttpClient client = null;
        HttpClientBuilder build = HttpClients.custom();
        client = build.build();
        return client;
    }
 
    /**
     * 进行Post请求
     * 
     * @param url  服务地址
     * @param json 添加json串
     * @return String结果
     */
    public static String doPost(String url, String json) {
        CloseableHttpClient httpClient = buildHttpClient();
        HttpPost httpPost = new HttpPost(url);
        String result = null;
        try {
            httpPost.setHeader("content-type", "application/xml;charset=UTF-8");//
            StringEntity se = new StringEntity(json, "utf-8");
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (ClientProtocolException e) {
            // logger.error("进行模拟HTTP请求时候发生异常 ,请求地址"+url,e);
        } catch (UnsupportedEncodingException e) {
            // logger.error("进行模拟HTTP请求时候发生异常,请求地址"+url,e);
        } catch (Exception e) {
            // logger.error("进行模拟HTTP请求时候发生异常,请求地址"+url,e);
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    
    
    
    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
        String url = "http://192.168.142.101:83/WebServiceForAndroid.asmx/FaultInfoTest";
        //传递参数的话 可以为 "key1=value1&key2=value2"的一串字符串
        String doPost = doPost(url,"key1=value1&key2=value2");
        System.out.println(doPost);
    }
    
    
}

 

解析返回的xml字符串
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
 
 
public class HttpClientTest {
 
    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws Exception {
        String xml = "<request> <param name='service'>single_trade_query </param><param name='_input_charset'>utf-8 </param><param name='partner'>2088001513232645 </param><param name='out_trade_no'>20090422577264 </param></request>";
        Document document = DocumentHelper.parseText(xml);
        Element root = document.getRootElement();
        List<Element> elements = root.elements();
        for (Iterator<Element> it = elements.iterator(); it.hasNext();) {
            Element element = it.next();
            List<Attribute> attributes = element.attributes();
            for (int i = 0; i < attributes.size(); i++) {
                Attribute attribute = attributes.get(i);
                if ("service".equals(attribute.getText())) {
                    System.out.println(element.getName() + "  :  " + element.getText());
                }
            }
        }
    }
    
    
    
    
    
    
 
    
}
 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值