JAVA使用HttpClient调用webservice接口

JAVA使用HttpClient调用webservice接口

关于HttpClient用法参考:
HttpClient-4.5.2官方教程完整翻译
官方教程原文链接
HttpClient下载地址:
链接:https://pan.baidu.com/s/1ScuxtWBdUvh-0xcLZRaa1Q
提取码:gbqb
调用webservice接口的代码:
个人笔记,自用勿喷!

package com.util;

import java.nio.charset.Charset;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 * 该方法为使用HttpClient调用webservice接口
 * @author LG
 *
 */
public class WsCallService {
	private static final Logger LOGGER = Logger.getLogger(WsCallService.class);
	
	/**
	 * 使用HttpClient调用webservice接口
	 * @param accInfoXml	请求参数,可参考SoapUI处入参拼接
	 * @param url	接口地址
	 * @param targetNamespace	接口命名空间
	 * @return
	 * @throws Exception
	 */
	public static String call(String accInfoXml, String url, String targetNamespace)
			throws Exception {
		//记录接口調用結果字符串
		String rev = "";
		// 获得Http客户端
		HttpClient httpclient = HttpClients.createDefault();
		// 响应模型
		HttpResponse response = null;
		try {
			// 创建Post请求
			HttpPost httppost = new HttpPost(url);
			// 设置Content-Type
			httppost.addHeader("Content-Type", "application/json; charset=UTF-8");
			httppost.addHeader("SOAPAction", targetNamespace);

			StringEntity data = new StringEntity(accInfoXml, Charset.forName("UTF-8"));	
			httppost.setEntity(data);
			// 由客户端执行请求
			response = httpclient.execute(httppost);
			// 检验状态码,如果成功接收数据
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {	//调用接口成功
				// 获取到返回结果,注意返回结构也是包装过后的,需要根据实际情况进行拆解
				rev = EntityUtils.toString(response.getEntity());
			} else {	//调用接口失败				
				rev = EntityUtils.toString(response.getEntity());
				LOGGER.error(rev);
				rev = "接口调用出错!";
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				EntityUtils.consumeQuietly(response.getEntity());
			}
		}
		return rev;
	}

	
}

  • 0
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Apache HttpClient异步调用WebServiceJava代码示例: ```java import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.MimeHeaders; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPHeader; import javax.xml.soap.SOAPMessage; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactoryConfigurationError; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.concurrent.FutureCallback; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.apache.http.util.EntityUtils; import org.w3c.dom.Document; import org.xml.sax.SAXException; public class AsyncWebServiceClient { private static final String SOAP_ACTION = "http://tempuri.org/HelloWorld"; private static final String ENDPOINT = "http://localhost/HelloWorldService/HelloWorldService.asmx"; private static final String SOAP_REQUEST = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" + " <soap:Body>\n" + " <HelloWorld xmlns=\"http://tempuri.org/\" />\n" + " </soap:Body>\n" + "</soap:Envelope>"; public static void main(String[] args) throws Exception { HttpClient httpClient = HttpAsyncClients.createDefault(); CloseableHttpAsyncClient httpclient = (CloseableHttpAsyncClient) httpClient; httpclient.start(); try { HttpPost httpPost = new HttpPost(ENDPOINT); httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8"); httpPost.setHeader("SOAPAction", SOAP_ACTION); StringEntity entity = new StringEntity(SOAP_REQUEST, ContentType.TEXT_XML.withCharset(StandardCharsets.UTF_8)); httpPost.setEntity(entity); Future<HttpResponse> future = httpclient.execute(httpPost, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse response) { try { HttpEntity responseEntity = response.getEntity(); String responseBody = EntityUtils.toString(responseEntity); System.out.println(responseBody); Document document = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(IOUtils.toInputStream(responseBody, StandardCharsets.UTF_8)); QName qName = new QName("http://tempuri.org/", "HelloWorldResponse"); SOAPBody soapBody = MessageFactory.newInstance().createMessage().getSOAPBody(); Document responseDocument = soapBody.getOwnerDocument(); SOAPHeader soapHeader = responseDocument.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "soap:Header"); soapBody.addChildElement(qName).appendChild(responseDocument.createTextNode("Hello World!")); SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(new MimeHeaders(), IOUtils.toInputStream(responseDocument.getDocumentElement().getTextContent(), StandardCharsets.UTF_8)); String soapResponse = IOUtils.toString(soapMessage.getSOAPPart().getContent(), StandardCharsets.UTF_8); System.out.println(soapResponse); } catch (IOException | UnsupportedOperationException | SOAPException | ParserConfigurationException | SAXException | TransformerFactoryConfigurationError | TransformerException e) { e.printStackTrace(); } } @Override public void failed(Exception ex) { ex.printStackTrace(); } @Override public void cancelled() { } }); HttpResponse response = future.get(); System.out.println(response); } finally { httpclient.close(); } } } ``` 以上代码使用Apache HttpClient库异步地调用了一个基于SOAP协议的Web Service,实现了将响应报文解析为SOAP消息的功能。在代码中,我们使用Java自带的XML解析器和SOAP库,也可以使用第三方库实现相同的功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值