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;
	}

	
}

发布了5 篇原创文章 · 获赞 0 · 访问量 60
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览