1.soapui新建一个webservice地址,例如http://www.webxml.com.cn/WebServices/TranslatorWebService.asmx?wsdl

2.

3.配置文件编写请求body

4.特殊说明请求sapUrl和charset的编写来自如图,saplength是参数长度

4.编写TranslatorWebServiceConfig

package com.tibet.foc.config;import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;@Component
@PropertySource("classpath:webservice/TranslatorWebService.properties")
public class TranslatorWebServiceConfig {@Value("${sapHead}")private String sapHead;@Value("${sapBody}")private String sapBody;@Value("${sapFoot}")private String sapFoot;@Value("${sapUrl}")private String sapUrl;@Value("${charText}")private String charText;@Value("${charSet}")private String charSet;@Value("${sapLength}")private int sapLength;public String getSapHead() {return sapHead;}public String getSapBody() {return sapBody;}public String getSapFoot() {return sapFoot;}public String getSapUrl() {return sapUrl;}public String getCharText() {return charText;}public String getCharSet() {return charSet;}public int getSapLength() {return sapLength;}
}

5.编写HttpConnectionUtils

package com.tibet.foc.util;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/*** @author wjw* @Description:* @date 2018/7/11*/
public class HttpConnectionUtils {/** 请求超时*/private final static int REQ_TIME_OUT = 10000;/** 连接超时*/private final static int CON_TIME_OUT = 10000;/** 设置请求和传输超时时间*/private static final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(REQ_TIME_OUT).setConnectTimeout(CON_TIME_OUT).build();/** 默认编码字符集*/private static final String DEFAULT_CHARSET = "utf-8";/** 重试次数 默认为三次*/private final static int DEFAULT_REPEAT_TIMES = 3;private static int repeatTime = DEFAULT_REPEAT_TIMES;private final static String DEFAULT_STR_MARK = "Dds12312weqweq1412qwe1";/*** @Description:*/private HttpConnectionUtils() {// TODO Auto-generated constructor stub}/*** Get请求 默认失败重试 (默认三次 不包含第一次)* @param httpUrl* @return* @throws IOException*/public static String doGet(String httpUrl) throws IOException {return doGetUrlEncoding(httpUrl, null, true);}/***请求返回cookie* @param httpUrl 请求路径* @param parameters 拼装请求参数* @param isRepeat 失败是否重试 (默认三次 不包含第一次)* @return* @throws IOException*/public static String doGetReturnHeaderCookies(String httpUrl,Map<String,String> parameters,boolean isRepeat) throws IOException {return doGetHttpRequest(httpUrl, parameters, isRepeat,true);}/***get 请求并对参数加密* @param httpUrl 请求路径* @param parameters* @param isRepeat 失败是否重试 (默认三次 不包含第一次)* @return* @throws IOException*/public static String doGetUrlEncoding(String httpUrl,Map<String,String> parameters,boolean isRepeat) throws IOException{return doGetHttpRequest(httpUrl, parameters, isRepeat, false);}/***get 请求* @param httpUrl 请求路径* @param parameters 参数* @param isRepeat  失败是否重试 (默认三次 不包含第一次)* @param headers 请求头信息* @return* @throws IOException*/public static String doGet(String httpUrl,Map<String,String> parameters,boolean isRepeat,Header ...headers) throws IOException {return doGetHttpRequest(httpUrl, parameters, isRepeat, false,headers);}/***Post请求* @param httpUrl 请求路径* @param parameters 请求参数* @param isRepeat 是否重试 如果true: 则自动重试三次 不包含第一次* @return* @throws IOException*/public static String doPost(String httpUrl,Map<String,String> parameters,boolean isRepeat) throws IOException {return doPost(null,httpUrl, parameters, isRepeat,new Header[]{});}/*** POST 提交* contentType 默认为 application/json* @param httpUrl 请求路径* @param requestBody 请求BODY* @param isRepeat 是否重试 默认重复3次 不包含第一次* @param header 头信息* @return* @throws IOException*/public static String doPost(String httpUrl,String requestBody,Boolean isRepeat,Header ...header) throws IOException {String returnDatas = doPostByRequestBody(null, httpUrl, requestBody, isRepeat,ContentType.APPLICATION_JSON, header);if(StringUtils.isBlank(returnDatas)) {if(StringUtils.isBlank(returnDatas)) {if(isRepeat) {AtomicInteger integer = new AtomicInteger(0);while(repeatTime != integer.get()) {System.out.println("正在重试第["+(integer.incrementAndGet())+"]次~");returnDatas = doPostByRequestBody(null, httpUrl, requestBody, isRepeat,ContentType.APPLICATION_JSON, header);if(StringUtils.equals(returnDatas, DEFAULT_STR_MARK) || StringUtils.isNotBlank(returnDatas)) {break;}}}}}return StringUtils.equals(returnDatas, DEFAULT_STR_MARK) ? null : returnDatas;}/*** HTTP RequestBody 参数* POST 提交* @Title: doPost* @param httpUrl 请求路径* @param requestBody 请求BODY* @param isRepeat 是否重试 默认重复3次 不包含第一次* @param header 头信息* @return* @author: Omar(OmarZhang)* @throws IOException* @throws IOException* @date: 2016年4月18日 下午6:12:36*/public static String doPost(String httpUrl,String requestBody,Boolean isRepeat,ContentType contentType,Header[] header) throws IOException {String returnDatas = doPostByRequestBody(null, httpUrl, requestBody, isRepeat,contentType, header);if(StringUtils.isBlank(returnDatas)) {if(StringUtils.isBlank(returnDatas)) {if(isRepeat) {AtomicInteger integer = new AtomicInteger(0);while(repeatTime != integer.get()) {System.out.println("正在重试第["+(integer.incrementAndGet())+"]次~");returnDatas = doPostByRequestBody(null, httpUrl, requestBody, isRepeat,contentType, header);if(StringUtils.equals(returnDatas, DEFAULT_STR_MARK) || StringUtils.isNotBlank(returnDatas)) {break;}}}}}return StringUtils.equals(returnDatas, DEFAULT_STR_MARK) ? null : returnDatas;}/*** 通过RequestBody* @Title: doPostByRequestBody* @param httpClient* @param httpUrl* @param requestBody* @param isRepeat* @param header* @param contentType* @return* @throws IOException* @author: Omar(OmarZhang)* @date: 2016年4月18日 下午6:23:01*/private static String doPostByRequestBody(CloseableHttpClient httpClient,String httpUrl,String requestBody,Boolean isRepeat,ContentType contentType, Header ...header) throws IOException  {if(httpClient == null) {httpClient =  HttpClients.custom().build();}HttpPost httpPost = new HttpPost(httpUrl);httpPost.setConfig(requestConfig);if(header != null && header.length > 0) {httpPost.setHeaders(header);}httpPost.setEntity(new StringEntity(requestBody,contentType));CloseableHttpResponse response = null;String returnData = null;HttpEntity respEntity = null;try {response = httpClient.execute(httpPost);respEntity = response.getEntity();if(respEntity != null) {returnData  = EntityUtils.toString(respEntity, DEFAULT_CHARSET);System.out.println("HTTP 请求 Response == >" +returnData);if(response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300) {//判断 如果请求成功 就算没有数据 也算成功 则表示不需要重试.标志加入if(StringUtils.isBlank(returnData)) {returnData = DEFAULT_STR_MARK;}}else {returnData = null;}}EntityUtils.consume(respEntity);} finally {HttpClientUtils.closeQuietly(response);HttpClientUtils.closeQuietly(httpClient);}return returnData;}/*** Post请求默认重试* 默认重试,重试次数3次不包括第一次* @Title: doPost* @param httpUrl 请求路径* @param parameters 请求参数* @param header  头信息设置* @return* @throws IOException*/public static String doPost(String httpUrl,Map<String, String> parameters,Header ...header) throws IOException {return doPost(null,httpUrl, parameters, true,header);}/*** Post请求默认重试* 默认不重试* @Title: doPost* @param httpClient 自定义 http客户端* @param httpUrl 请求路径* @param parameters 请求参数* @param header 头信息设置* @return* @throws IOException*/public static String doPost(CloseableHttpClient httpClient,String httpUrl,Map<String, String> parameters,Header ...header) throws IOException {return doPost(httpClient,httpUrl, parameters, false,header);}/*** Post请求* @Title: doPost* @param httpUrl 请求路径* @param parameters 请求参数* @param isRepeat 是否重试 如果true: 则自动重试三次 不包含第一次* @param header 头信息设置* @return* @throws IOException*/private static String doPost(CloseableHttpClient httpClient,String httpUrl,Map<String, String> parameters,boolean isRepeat, Header ...header) throws IOException {String returnDatas = null;returnDatas = doPostHttpRequet(httpClient,httpUrl,parameters,header);if(StringUtils.isBlank(returnDatas)) {if(isRepeat) {AtomicInteger integer = new AtomicInteger(0);while(repeatTime != integer.get()) {System.out.println("正在重试第["+(integer.incrementAndGet())+"]次~");returnDatas = doPostHttpRequet(httpClient,httpUrl,parameters,header);if(StringUtils.equals(returnDatas, DEFAULT_STR_MARK) || StringUtils.isNotBlank(returnDatas)) {break;}}}}return StringUtils.equals(returnDatas, DEFAULT_STR_MARK) ? null : returnDatas;}/*** Post 请求* @param httpclient* @param httpUrl* @param parameters* @param header* @return* @throws IOException*/private static String doPostHttpRequet(CloseableHttpClient httpclient,String httpUrl, Map<String, String> parameters, Header ...header) throws IOException {if(httpclient == null) {httpclient = HttpClients.custom().build();}HttpPost httpPost = new HttpPost(httpUrl);httpPost.setConfig(requestConfig);List<NameValuePair> valuePairs = new LinkedList<NameValuePair>();String returnData = null;if(MapUtils.isNotEmpty(parameters)) {for(Map.Entry<String, String> entry : parameters.entrySet()) {valuePairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));}}UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(valuePairs, DEFAULT_CHARSET);if(header != null && header.length > 0) {httpPost.setHeaders(header);}httpPost.setEntity(urlEncodedFormEntity);CloseableHttpResponse response = httpclient.execute(httpPost);try {HttpEntity respEntity = response.getEntity();if(respEntity != null) {returnData = EntityUtils.toString(respEntity, DEFAULT_CHARSET);System.out.println("HTTP 请求 Response == >" +returnData);if(response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300) {//判断 如果请求成功 就算没有数据 也算成功 则表示不需要重试.标志加入if(StringUtils.isBlank(returnData)) {returnData = DEFAULT_STR_MARK;}}else {returnData = null;}}EntityUtils.consume(respEntity);} finally {HttpClientUtils.closeQuietly(response);HttpClientUtils.closeQuietly(httpclient);}return returnData;}/*** get 请求* @param httpUrl* @param parameters* @param isRepeat* @param isReturnCookies* @param headers* @return* @throws IOException*/private static String doGetHttpRequest(String httpUrl, Map<String, String> parameters, boolean isRepeat, boolean isReturnCookies , Header ...headers)throws IOException {String appendParametersStr  =  buildQuery(parameters);if(StringUtils.isNotBlank(appendParametersStr)) {httpUrl = httpUrl+"?"+appendParametersStr;}String returnDatas = null;returnDatas = httpGetConnection(httpUrl,true, headers);if(StringUtils.isBlank(returnDatas)) {if(isRepeat) {AtomicInteger integer = new AtomicInteger(0);while(repeatTime != integer.get()) {System.out.println("正在重试第["+(integer.incrementAndGet())+"]次~");returnDatas = httpGetConnection(httpUrl,true, headers);if(StringUtils.equals(returnDatas, DEFAULT_STR_MARK) || StringUtils.isNotBlank(returnDatas)) {break;}}}}return StringUtils.equals(returnDatas, DEFAULT_STR_MARK) ? null : returnDatas;}public static void main(String[] args) {try {System.out.println(doGet("http://www.baidu.com"));} catch (IOException e) {e.printStackTrace();}}/*** 创建Http连接请求* @param httpUrl* @param parameters* @return* @throws ClientProtocolException* @throws IOException*/public static CloseableHttpClient getHttpClient(String httpUrl, Map<String, String> parameters) throws ClientProtocolException, IOException {CloseableHttpClient httpClient = HttpClients.createDefault();String appendParametersStr  =  buildQuery(parameters);if(StringUtils.isNotBlank(appendParametersStr)) {httpUrl = httpUrl+"?"+appendParametersStr;}HttpGet httpGet = new HttpGet(httpUrl);//httpGet.setConfig(requestConfig);httpClient.execute(httpGet);return httpClient;}private static String httpGetConnection(String httpUrl,boolean isReturnCookies,Header[] headers) throws IOException{BasicCookieStore cookieStore = new BasicCookieStore();CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();HttpGet httpGet = new HttpGet(httpUrl);httpGet.setConfig(requestConfig);String returnData = null;HttpEntity respEntity = null;CloseableHttpResponse responsere = null;if(headers != null && headers.length > 0) {httpGet.setHeaders(headers);}try {responsere = httpclient.execute(httpGet);respEntity = responsere.getEntity();if(respEntity != null) {returnData = EntityUtils.toString(respEntity, DEFAULT_CHARSET);System.out.println("HTTP 请求 Response == >" +returnData);//Http 返回状态码 200 表示请求成功if(responsere.getStatusLine().getStatusCode() >= 200 && responsere.getStatusLine().getStatusCode() < 300) {// 如果请求成功 就算没有数据 也算成功 则表示不需要重试.标志加入if(StringUtils.isBlank(returnData)) {returnData = DEFAULT_STR_MARK;}}else {returnData = null;}}EntityUtils.consume(respEntity);} catch (Exception e) {e.printStackTrace();}finally{HttpClientUtils.closeQuietly(responsere);HttpClientUtils.closeQuietly(httpclient);}return returnData;}/*** 请求参数拼装* 默认UTF-8字符集* 默认参数加密* @Title: buildQuery* @param params* * @return* @throws IOException*/public static String buildQuery(Map<String, String> params) throws IOException {return buildQuery(params, DEFAULT_CHARSET,true);}/***加密请求参数* @param params 参数* @param charset 加密编码* @param isEncoding 是否加密* @return* @throws IOException*/public static String buildQuery(Map<String, String> params, String charset,boolean isEncoding) throws IOException {if (MapUtils.isEmpty(params)) {return null;}StringBuilder query = new StringBuilder();Set<Entry<String, String>> entries = params.entrySet();boolean hasParam = false;for (Entry<String, String> entry : entries) {String name = entry.getKey();String value = entry.getValue();// 忽略参数名或参数值为空的参数if (StringUtils.isNotBlank(name)&&StringUtils.isNotBlank(value)) {if (hasParam) {query.append("&");} else {hasParam = true;}query.append(name).append("=").append((isEncoding ? URLEncoder.encode(value, charset):value));}}return query.toString();}
}

6.pom添加http工具依赖

<dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.7</version>
</dependency>
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.4</version>
</dependency>
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.5.4</version>
</dependency>

7.编写SapTranslatorHandler

package com.tibet.foc.handler;import com.tibet.foc.config.TranslatorWebServiceConfig;
import com.tibet.foc.util.HttpConnectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.entity.ContentType;
import org.springframework.stereotype.Component;import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;/**
 * @author wjw
 * @Description: webservice
 * @date 2018/7/11
 */
@Component("sapTranslatorHandler")
public class SapTranslatorHandler {@Resource
   private TranslatorWebServiceConfig weatherConfig;/**
     * 组装参数
     * @param cityName
     * @return
     */
    private Object[] setRequestBodyToSapField(String cityName){Object[] object = new Object[weatherConfig.getSapLength()];object[0] = cityName;return object;}public Map<String,Object> pushTranslatToSap(String cityName) throws IOException {Map<String,Object> resultMap = new HashMap<String,Object>();Object[] orderObject = setRequestBodyToSapField(cityName);String tempSapBody = String.format(weatherConfig.getSapBody(), orderObject);StringBuffer tempRequestBody = new StringBuffer();tempRequestBody.append(weatherConfig.getSapHead()).append(tempSapBody).append(weatherConfig.getSapFoot());String requestBody = tempRequestBody.toString();ContentType contentType = ContentType.create(weatherConfig.getCharText());String resultBody = null;try {resultBody = HttpConnectionUtils.doPost(weatherConfig.getSapUrl(), requestBody, true,contentType,new Header[]{});if(StringUtils.isBlank(resultBody)) {resultMap.put("flag", false);resultMap.put("message", "调用中文 <-> 英文双向翻译 WEB 服务 接口失败!");return resultMap;}resultMap.put("flag", true);} catch (Exception e) {e.printStackTrace();resultMap.put("message", "中文 <-> 英文双向翻译 WEB 服务 接口连接超时!");resultMap.put("flag", false);}return resultMap;}}

8.创建测试类TranslatorHandlerTest

package com.tibet.webservice;import com.tibet.foc.FOCStarter;
import com.tibet.foc.handler.SapTranslatorHandler;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;import javax.annotation.Resource;
import java.io.IOException;/*** @author wjw* @Description: ${todo}(用一句话描述该文件做什么)<br>* @date 2018/6/29*/
@SpringBootTest(classes = FOCStarter.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class TranslatorHandlerTest {@Resourceprivate SapTranslatorHandler translatorHandler;@Testpublic void translator() throws IOException {translatorHandler.pushTranslatToSap("test");}}

9.查看运行效果

httpclient请求webservice接口相关推荐

  1. HttpClient调用WebService接口

    文章目录 前言 WebService是什么? WebService原理? HttpClient是什么? HttpClient应用场景? 使用HttpClient调用WebService接口 1.创建H ...

  2. JAVA使用HttpClient调用webservice接口

    JAVA使用HttpClient调用webservice接口 关于HttpClient用法参考: HttpClient-4.5.2官方教程完整翻译 官方教程原文链接 HttpClient下载地址: 链 ...

  3. Java通过soap1.1请求webservice接口

    首先获取到soap接口的wsdl地址,通过soapUI工具打开. 前提需要在配置的插件工具配置axis地址,axis-1_4可在我的资源里下载. 选择导出包的位置,生成代码. 将代码复制到java项目 ...

  4. Html中使用jquery通过Ajax请求WebService接口以及跨域问题解决

    场景 VS2019新建WebService/Web服务/asmx并通过IIS实现发布和调用: VS2019新建WebService/Web服务/asmx并通过IIS实现发布和调用_霸道流氓气质的博客- ...

  5. jmeter压测学习47-发soap请求测试webservice接口

    前言 jmeter3 的版本可以新建一个SOAP/XML-RPC Request 的请求,直接测试webservice的接口. jmeter5.1.1 版本已经去掉了自带的SOAP/XML-RPC R ...

  6. 使用Fiddler调用WebService接口,模拟发HTTP请求

    1.百度一个免费WebService接口 如:天气预报http://www.webxml.com.cn/WebServices/WeatherWebService.asmx 其下有一个方法 2.打开F ...

  7. 使用commons httpclient请求https协议的webservice

    使commons httpclient支持https协议类,是commons httpclient import java.io.IOException; import java.net.InetAd ...

  8. ajax调用远程webservice,ajax跨域请求调用webservice接口

    最近忽然想学习webservice,一直不知道如何跨域调用调用.若是都在同一个项目,相信你们都知道了?特此整理一下关键点,权当学习.javascript 1.WebService 接口编写.这里不在赘 ...

  9. soap+wsimport的webservice接口客户端实现

    一个自定义实现的soap接口客户端调用工具,已在实际项目中使用过,且经过了生产环境检验. 使用方法: (1)先用jdk自带的wsdl工具导出接口java源码:wsimport -s . xxx.wsd ...

最新文章

  1. python有趣的小项目-Python几个有趣和特别的小故事
  2. restful,RESTful API 设计,GET/PUT/DELETE/POST
  3. max file descriptors_年轻族的战场!宋MAX强势对比嘉际
  4. 二十、PHP框架Laravel学习笔记——模型的作用域
  5. Orcale的存储过程
  6. 第 8 章 查找算法
  7. 如何理解linux多用户多任务
  8. php 查找php配置文件php.ini所在路径的二种方法
  9. (5) IFC 总体架构 (Industry Foundation Class)
  10. 百度暑期前端实训DAY1心得
  11. 习题3第五题:分析习题2第四题所述的患者监护系统。试用实体联系图描绘本系统的数据对象,画出本系统的顶层IPO图。
  12. 笔记本联想小新Air14重装win10后触摸板失灵解决方案
  13. 计算机硬盘 打开很慢,电脑硬盘运行速度慢如何解决 电脑硬盘运行速度慢解决方法【介绍】...
  14. libusb android 编译,Android如何对libusb进行编译和使用
  15. 做亚马逊的工作,到底辛不辛苦?值得吗?
  16. PHP 按一定比例压缩图片,保持清晰度
  17. 游戏引擎不仅是代码,更多的是完善的工具
  18. 一个密码本(ACodebook)介绍
  19. 切换window窗口
  20. php 做一个题目木选项,GRE PPII阅读解析版

热门文章

  1. bigdata学习笔记--01 Linux基础--Linux目录结构
  2. 网页中链接中图片的下载
  3. 思科ACS5.8最新搭建教程-亲测可用
  4. sphinx 编码 php文档,用Sphinx编写技术文档
  5. NL80211使用笔记
  6. Sublime Text 全程图文指引
  7. centos7软件安装更新
  8. JS / JQ 学习记录
  9. drv8833 马达控制
  10. php安全新闻早八点-Microdoor-第二季