zoukankan      html  css  js  c++  java
  • java通过HttpClient方式和HttpURLConnection方式调用WebService接口

    1.引入maven依赖:

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

    2.请求工具类:

    package com.hanvon.iface.web.utils;

    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 org.apache.log4j.Logger;
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.nio.charset.Charset;


    /**
    * webservice发送请求工具类
    * Author:lsf
    * Date:19-01-08
    */
    public class WebServiceUtil {
    static int socketTimeout = 30000;// 请求超时时间
    static int connectTimeout = 30000;// 传输超时时间
    static Logger logger = Logger.getLogger(WebServiceUtil.class);

    /**
    * 使用SOAP发送消息(HttpClient方式)
    *
    * @param postUrl
    * @param soapXml
    * @param soapAction
    * @return
    */
    public static String doPostSoap(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");
    logger.info("response:" + retStr);
    }
    // 释放资源
    closeableHttpClient.close();
    } catch (Exception e) {
    logger.error("请求出错!", e);
    }
    return retStr;
    }

    /**
    * 使用HttpURLConnection方式连接
    * @param soapurl
    * @param soapXML
    * @return
    * @throws IOException
    */
    public static String urlConnectionUtil(String soapurl,String soapXML) throws IOException {
    //第一步:创建服务地址
    //http://172.25.37.31:8080/PeopleSoftService/getPerson.wsdl
    URL url = new URL(soapurl);
    //第二步:打开一个通向服务地址的连接
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    //第三步:设置参数
    //3.1发送方式设置:POST必须大写
    connection.setRequestMethod("POST");
    //3.2设置数据格式:content-type
    connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
    //3.3设置输入输出,因为默认新创建的connection没有读写权限,
    connection.setDoInput(true);
    connection.setDoOutput(true);
    //第四步:组织SOAP数据,发送请求
    //将信息以流的方式发送出去
    OutputStream os = connection.getOutputStream();
    os.write(soapXML.getBytes());
    StringBuilder sb = new StringBuilder();
    //第五步:接收服务端响应,打印
    int responseCode = connection.getResponseCode();
    if(200 == responseCode){//表示服务端响应成功
    //获取当前连接请求返回的数据流
    InputStream is = connection.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    // StringBuilder sb = new StringBuilder();
    String temp = null;
    while(null != (temp = br.readLine())){
    sb.append(temp);
    }
    is.close();
    isr.close();
    br.close();
    }
    os.close();
    return sb.toString();
    }

    }

    ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    springboot中通过RestTemplate调用

    @SpringBootApplication
    @ServletComponentScan
    public class Springboot02 extends SpringBootServletInitializer{

    public static void main(String[] args) {
    SpringApplication.run(Springboot02.class, args);
    }
    @Bean
    public RestTemplate getRestTemplate(){
    return new RestTemplate();
    }

    }

    @RestController
    public class RService {
    @Autowired
    private RestTemplate restTemplate;
    @RequestMapping("/weather")
    public String get(){
    String string=restTemplate.getForEntity("http://localhost:8080/test",String.class).getBody();
    return string;
    }
    }
  • 相关阅读:
    Kafka事务机制
    RabbitMQ事务机制
    RocketMQ事务消息
    No 'Access-Control-Allow-Origin' header is present on the requested resource.'Ajax跨域访问解决方案
    java + eclipse 工作环境快速配置
    查找.bashrc文件并设置linux快捷命令
    headers参数传值类型
    无需会员将有道云笔记脑图转换xmind
    使用goland调试远程代码
    nginx配置文件使用环境变量
  • 原文地址:https://www.cnblogs.com/metu/p/10567269.html
Copyright © 2011-2022 走看看