httpclient调用webService

httpclient妙用一 httpclient作为客户端调用webservice http://aperise.iteye.com/blog/2223454
httpclient妙用二 httpclient保持会话登录 http://aperise.iteye.com/blog/2223470
httpclient连接池 http://aperise.iteye.com/blog/2295153
------------------------------------------------------------------------------------------------------------------------

   maven依赖如下:  
<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.3.2</version>
      </dependency>
      <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>fluent-hc</artifactId>
        <version>4.3.2</version>
      </dependency>
      <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>http-core</artifactId>
        <version>4.3.2</version>
</dependency>

  

import java.nio.charset.Charset;
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;
 
public class HttpClientCallSoapUtil {
	static int socketTimeout = 30000;// 请求超时时间
	static int connectTimeout = 30000;// 传输超时时间
	static Logger logger = Logger.getLogger(HttpClientCallSoapUtil.class);
 
	/**
	 * 使用SOAP1.1发送消息
	 * 
	 * @param postUrl
	 * @param soapXml
	 * @param soapAction
	 * @return
	 */
	public static String doPostSoap1_1(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("exception in doPostSoap1_1", e);
		}
		return retStr;
	}
 
	/**
	 * 使用SOAP1.2发送消息
	 * 
	 * @param postUrl
	 * @param soapXml
	 * @param soapAction
	 * @return
	 */
	public static String doPostSoap1_2(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",
					"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");
				logger.info("response:" + retStr);
			}
			// 释放资源
			closeableHttpClient.close();
		} catch (Exception e) {
			logger.error("exception in doPostSoap1_2", e);
		}
		return retStr;
	}
 
	public static void main(String[] args) {
		String orderSoapXml = "<?xml version = \"1.0\" ?>"
				+ "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservices.b.com\">"
				+ "   <soapenv:Header/>"
				+ "   <soapenv:Body>"
				+ "      <web:order soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
				+ "         <in0 xsi:type=\"web:OrderRequest\">"
				+ "            <mobile xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">?</mobile>"
				+ "            <orderStatus xsi:type=\"xsd:int\">?</orderStatus>"
				+ "            <productCode xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">?</productCode>"
				+ "         </in0>" + "      </web:order>"
				+ "   </soapenv:Body>" + "</soapenv:Envelope>";
		String querySoapXml = "<?xml version = \"1.0\" ?>"
				+ "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservices.b.com\">"
				+ "   <soapenv:Header/>"
				+ "   <soapenv:Body>"
				+ "      <web:query soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
				+ "         <in0 xsi:type=\"web:QueryRequest\">"
				+ "            <endTime xsi:type=\"xsd:dateTime\">?</endTime>"
				+ "            <mobile xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">?</mobile>"
				+ "            <startTime xsi:type=\"xsd:dateTime\">?</startTime>"
				+ "         </in0>" + "      </web:query>"
				+ "   </soapenv:Body>" + "</soapenv:Envelope>";
		String postUrl = "http://localhost:8080/services/WebServiceFromB";
		//采用SOAP1.1调用服务端,这种方式能调用服务端为soap1.1和soap1.2的服务
		doPostSoap1_1(postUrl, orderSoapXml, "");
		doPostSoap1_1(postUrl, querySoapXml, "");
 
		//采用SOAP1.2调用服务端,这种方式只能调用服务端为soap1.2的服务
		//doPostSoap1_2(postUrl, orderSoapXml, "order");
		//doPostSoap1_2(postUrl, querySoapXml, "query");
	}

  

优点:

       1.使用httpclient作为客户端调用webservice,不用关注繁琐的webservice框架,只需找到SOAP消息格式,添加httpclient依赖就行。

       2.使用httpclient调用webservice,建议采用soap1.1方式调用,经测试使用soap1.1方式能调用soap1.1和soap1.2的服务端。

 

       缺点:

       唯一的缺点是,你得自己解析返回的XML,找到你关注的信息内容。
————————————————

原文链接:https://blog.csdn.net/zilong_zilong/article/details/53932667

原文地址:https://www.cnblogs.com/ixtao/p/14876614.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


1.使用ajax调用varxhr;functioninvoke(){if(window.ActiveXObject){xhr=newActiveXObject("Microsoft.XMLHTTP");}else{xhr=newXMLHttpRequest();}//指定请求地址varurl="http://127.0.0.1:7777/hello?wsdl";//
               好不容易把WebService服务器端搭建起来,我们还需要客户端程序也同样跑起来才能够进行和服务器端程序的通信: 在这篇文章里面,我会先自己写代码去实现调用WebService服务器端程序,接下来,通过IDEA配置的方式来调用WebService服务端: 首先,我写了一个W
1新建一个工程项目用来做服务端增加一个MyService1类文件packagecom.zns.ws;importjavax.jws.WebMethod;importjavax.jws.WebService;importjavax.xml.ws.Endpoint;@WebServicepublicclassMyService1{publicstaticvoidmain(String[]args){
packagecom.transsion.util;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.URL;importjava.net.URLConnection;importcom.alibaba.druid.util.Base64;importcom.tra
再生产wsdl文件时重写描述文件1usingSystem;2usingSystem.Collections.Generic;3usingSystem.Linq;4usingSystem.Web;5usingSystem.Web.Services.Description;67namespaceStrongSoftManage.Web.App8{9publicclassSoapExtens:SoapExtensi
一般情况下,使用eclipse自带的jax-ws生成webservice会自动生成2个类:ContractConnector.java packagecom.wonders.webservice.contract;importjava.text.DecimalFormat;importjava.text.ParseException;importjava.text.SimpleDateFormat;importjava.util.Date;i
一、WebService概述1.1什么是WebService 基于Web的服务:服务器端整出一些资源让客户端应用访问(获取数据) 一个跨语言、跨平台的规范(抽象)所谓跨编程语言和跨操作平台,就是说服务端程序采用java编写,客户端程序则可以采用其他编程语言编写,反之亦然!跨操作系统平台则是指服务
一、什么是CXF?    ApacheCXF=Celtix+Xfire,开始叫ApacheCeltiXfire,后来更名为ApacheCXF了,以下简称为CXF。ApacheCXF是一个开源的webServices框架,CXF帮助您构建和开发webServices,它支持多种协议,比如:SOAP1.1,1,2 XML/HTTP、RESTful或者CORBA。  
工具IDEA一、构建项目1、选择SpringInitializr2、填写项目信息3、勾选webService4、勾选Thymeleaf5、项目建立完成,启动类自动生成二、写个Controller启动服务。浏览器访问/hello接口。 
1.环境win764位,vs20102.新建一个asp.netweb应用程序(同上一篇)3.添加一个web引用,引用上一篇创建的服务。注意不是服务引用。如下图 
WebService之WSDL文件讲解   恩,我想说的是,是不是经常有人在开发的时候,特别是和第三方有接口的时候,走的是SOAP协议,然后用户给你一个WSDL文件,说按照上面的进行适配,嘿嘿,这个时候,要是你以前没有开发过,肯定会傻眼,那如果你想学习的话,就认真的看下面的讲解咯:一、WSDL概述  
在websrvice发布文件的webconfig中加入<httpRuntimemaxRequestLength="102400"/> <webServices>     <protocols>       <addname="HttpPost"/>       <addname="HttpGet"/>     </protocols>   
 代码比较简单,按照如下来操作即可,只是jar包有很多问题,比如找不到classnotFondspring、以及找不到xfile.xml、以及xfile.xml中的一个参数问题,以及2.0 spring。jar和spring1.6.2冲突问题,总之这个小demo报了一堆错误,其实都是jar的问题,为了让大家减少这方面的错误,所以我提供
 一、soapUI简介SOAP:   WebService通过Http协议发送请求和接收结果时,发送的请求内容和结果内容都采用XML格式封装,并增加了一些特定的HTTP消息头,以说明HTTP消息头的内容格式,这些特定的HTTP消息头和XML内容格式就是SOAP协议。SOAP提供了标准的RPC方法来调用WebService。 
参考,感谢https://blog.csdn.net/hj7jay/article/details/727224381.环境:win764位,jdk1.8.0_201 EclipseJavaEEIDEforWebDevelopers.Version:Mars.1Release(4.5.1)2.创建一个普通的java项目,名字是TheService在src目录下创建一个com.hyan.service包,在此包下创建
CXF实现RestfulWebService基础示例一、写在前面IDE:IDEA14JDK:1.7CXF:2.6.2示例来源:%CXF_HOME%\samples\jax_rs\basic发布方式:JAXRSServerFactoryBean的create()方法调用方式:URL的openStream()方法、HttpClient的executeMethod()方法二、服务端(Java项目)1.准备Jar包
封装helper类:classWebServiceHelper{///<summary>///1.get请求http方法///</summary>///<paramname="url">基础url</param>///<paramname="method">请求方法</param>///<paramnam
.net客户端调用java或.netwebservice进行soapheader验证最近项目中有业务需要跨平台调用web服务,客户端和服务器之间采用非对称加密来保证数据的安全性,webservice的安全验证基于soapheader。借此机会,顺便整理一下调用.netwebservice和javawebservice的验证方式,记录下来。
Node.jshttps://www.cnblogs.com/goldlong/p/8027997.htmlQQ音乐apihttps://juejin.im/post/5a35228e51882506a463b172#heading-11?tdsourcetag=s_pcqq_aiomsgGit把本地仓库上传到GitHbubhttps://blog.csdn.net/zamamiro/article/details/70172900git删除本地仓库https://blog.cs
转载自:孤傲苍狼 WebService学习总结(三)——使用JDK开发WebService一、WebService的开发手段使用Java开发WebService时可以使用以下两种开发手段1、 使用JDK开发(1.6及以上版本)-->详见:本文2、使用CXF框架开发-->详见:其他文章二、使用JDK开发WebServi