SpringBoot HttpClient方式调用Webservice接口

8 篇文章 0 订阅
3 篇文章 0 订阅

1.引入JAR包

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.12</version>
</dependency>

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpcore</artifactId>
	<version>4.4.13</version>
</dependency>

2.Java代码

import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.apache.commons.lang3.StringUtils;
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.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * Http方式调用webservice接口
 * */
public class HttpWS {
    static int socketTimeout = 30000;// 请求超时时间
    static int connectTimeout = 30000;// 传输超时时间

    /**
     * 使用SOAP1.1发送消息
     *
     * @param postUrl webservice地址
     * @param soapXml 发送的报文
     * @param soapAction
     * @param user 用户名
     * @param pass 密码
     * @return
     */
    public static String postSoap1_1(String postUrl, String soapXml, String soapAction, String user,String pass) {
        String retStr = "";
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(reWriteUrl(postUrl));

        // 需要用户名密码验证
        if(StringUtils.isNotEmpty(user)){
            httpPost.addHeader(new BasicHeader("Authorization","Basic "
                    + Base64.encode((user+":"+pass).getBytes())));
        }

        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectTimeout).build();
        httpPost.setConfig(requestConfig);

        if(soapAction != null){
            soapAction = "";
        }
        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");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                if (closeableHttpClient != null)
                    closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return retStr;
    }

    /**
     * 使用SOAP1.2发送消息
     *
     * @param postUrl
     * @param soapXml
     * @param soapAction
     * @param user
     * @param pass
     * @return
     */
    public static String postSoap1_2(String postUrl, String soapXml, String soapAction, String user,String pass) {
        String retStr = "";
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(postUrl);

        // 需要用户名密码验证
        if(StringUtils.isNotEmpty(user)){
            httpPost.addHeader(new BasicHeader("Authorization","Basic "
                    + Base64.encode((user+":"+pass).getBytes())));
        }

        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectTimeout).build();
        httpPost.setConfig(requestConfig);

        if(soapAction != null){
            soapAction = "";
        }
        try {
            httpPost.setHeader("Content-Type", "application/soap+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");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                if (closeableHttpClient != null)
                    closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return retStr;
    }

    public static String reWriteUrl(String wsdlUrl){
        if(wsdlUrl.endsWith("?wsdl")){
            int index = wsdlUrl.indexOf("?wsdl");
            String address = wsdlUrl;
            if (index > 0) {
                address = wsdlUrl.substring(0, index);
            }
            return address;
        }else {
            return wsdlUrl;
        }
    }

    //测试
    public static void main(String args[]){
        String postUrl = "http://localhost:9080/test/services/TestWS?wsdl";
        String soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:com=\"http://com.test.other.service\">" +
                "   <soapenv:Header/>" +
                "   <soapenv:Body>" +
                "      <com:testWS>" +
                "         <name>?</name>" +
                "      </com:testWS>" +
                "   </soapenv:Body>" +
                "</soapenv:Envelope>";

        String username = "test";
        String password = "123456";
        String result = postSoap1_1(postUrl, soapXml, "",username,password);
        System.out.println(result);
    }
}

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是使用HttpClient调用天气预报接口的Spring Boot示例: 1. 添加HttpClient和Jackson依赖 ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> ``` 2. 创建HttpClient实例 ```java @Configuration public class HttpClientConfig { @Bean public CloseableHttpClient httpClient() { return HttpClients.createDefault(); } @Bean public HttpClientService httpClientService(CloseableHttpClient httpClient) { return new HttpClientService(httpClient); } } ``` 3. 创建HttpClientService类 ```java public class HttpClientService { private final CloseableHttpClient httpClient; public HttpClientService(CloseableHttpClient httpClient) { this.httpClient = httpClient; } public String get(String url) throws IOException { HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response = httpClient.execute(httpGet); try { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } } finally { response.close(); } return null; } } ``` 4. 创建Weather类 ```java public class Weather { private String date; private String week; private String weather; private String temp; private String humidity; private String wind; // getter and setter } ``` 5. 创建WeatherService类 ```java @Service public class WeatherService { private final HttpClientService httpClientService; public WeatherService(HttpClientService httpClientService) { this.httpClientService = httpClientService; } public List<Weather> getWeather(String city) throws IOException { String url = "http://wthrcdn.etouch.cn/weather_mini?city=" + city; String json = httpClientService.get(url); ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.readTree(json); JsonNode dataNode = rootNode.path("data"); List<Weather> weatherList = new ArrayList<>(); for (JsonNode node : dataNode.path("forecast")) { Weather weather = mapper.treeToValue(node, Weather.class); weatherList.add(weather); } return weatherList; } } ``` 6. 测试WeatherService ```java @RestController public class WeatherController { private final WeatherService weatherService; public WeatherController(WeatherService weatherService) { this.weatherService = weatherService; } @GetMapping("/weather") public List<Weather> getWeather(@RequestParam String city) throws IOException { return weatherService.getWeather(city); } } ``` 现在,你可以通过访问http://localhost:8080/weather?city=北京来获取北京的天气预报信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值