使用HttpClient进行http post/get方法的调用,以及使用dom4j解析xml

import java.io.IOException;

import java.util.List;



import javax.servlet.ServletInputStream;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.HttpStatus;

import org.apache.commons.httpclient.NameValuePair;

import org.apache.commons.httpclient.methods.PostMethod;

import org.apache.commons.httpclient.params.HttpMethodParams;

import org.apache.commons.io.IOUtils;

import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.DocumentHelper;

import org.dom4j.Element;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;



import com.eecn.warehouse.api.model.Address;

import com.eecn.warehouse.api.model.User;

import com.eecn.warehouse.utils.FoodBase;

import com.frogsing.common.api.open.storage.hy.TCustomer;

import com.frogsing.common.open.tools.xmlUtils;

import com.google.common.collect.Lists;

import com.thoughtworks.xstream.XStream;



@Controller

@RequestMapping(value = {"/api"})

public class ApiAction {

	private static Logger logger = LoggerFactory.getLogger(ApiAction.class);

	public static final String SERVER_URL = "http://192.168.1.100/api/StorageApi";

	

	@RequestMapping(value = {"/StorageApi"}, method = RequestMethod.POST)

	public String storageApi(TCustomer model, HttpServletRequest request, HttpServletResponse response) throws DocumentException {

		String xml = request.getParameter("xml");

		String signature = request.getParameter("signature");

		//************************http client*******************//

		PostMethod postMethod = null;

		try {

			// 构造HttpClient的实例

			HttpClient httpClient = new HttpClient();

			// 设置连接超时

			httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);

			// 设置字符集

			httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

			// 创建POST方法的实例

			postMethod = new PostMethod(SERVER_URL);

			// 使用系统提供的默认的恢复策略 该策略在碰到IO异常的时候将自动重试3次。

			postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 20000);

			// 异常时,重试处理器

			postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());



			//参数

			NameValuePair[] nameValuePairs = new NameValuePair[2];

			nameValuePairs[0] = new NameValuePair("xml", xml);

			nameValuePairs[1] = new NameValuePair("signature", signature);



			// 将参数加入到请求方法中

			postMethod.setRequestBody(nameValuePairs);

			// 发送连接

			int statusCode = httpClient.executeMethod(postMethod);



			if (statusCode == HttpStatus.SC_OK) {



				String result = postMethod.getResponseBodyAsString();

				logger.info("返回数据1:" + result);

				logger.info("字符集:" + postMethod.getResponseCharSet());

				String rspXml = new String(postMethod.getResponseBody(), "UTF-8");

				logger.info("返回数据2:" + rspXml);



				Document document = DocumentHelper.parseText(rspXml);

				

				Element signatureNode = (Element)document.selectSingleNode("//signature");

				Element dataNode = (Element)document.selectSingleNode("//data");

				

				String signXml = signatureNode.getText();

				String dataXml = dataNode.getText();

				

				String pureXml = FoodBase.decodeXml(dataXml);

				

				request.setAttribute("pureXml", pureXml);

				request.setAttribute("signXml", signXml);

			}

		} catch (Exception e) {

			logger.error("http client invoke error.", e);

		} finally {

			if (postMethod != null) {

				postMethod.releaseConnection();

			}

		}

		

		

		//******************************************************//

		ServletInputStream inputStream = null;

		String rspXml = null;

		try {

			inputStream = request.getInputStream();

			rspXml = IOUtils.toString(inputStream, "UTF-8");

		} catch (IOException e) {

			logger.error("读取交易仓单返回数据错误.", e);

		}

		

		return "api/storage";

	}

	

	@RequestMapping(value = {"/MarketApi"}, method = RequestMethod.POST)

	public String marketApi(HttpServletRequest request, HttpServletResponse response) {

		

		return "api/market";

	}

	

	public static void main(String[] args) {

		XStream xstream = new XStream();

		xstream.alias("User", User.class);

		xstream.alias("Address", Address.class);

		

		//xStream.aliasAttribute(User.class, "name", "name");

		xstream.useAttributeFor(User.class, "name");

		

		

		List<Address> addressList = Lists.newArrayList();

		for (int i = 0; i < 3; i++) {

			Address address = new Address();

			address.setProvince("浙江");

			addressList.add(address);

		}

		User user = new User();

		user.setAddressList(addressList);

		

		user.setAccount("asddaa");

		user.setAge(23);

		user.setGender(0);

		user.setName("zhang");

		

		System.out.println(xstream.toXML(user));

		

		System.out.println(xmlUtils.toEntityXml(user));

	}

}

get方法类似。

你可能感兴趣的:(httpclient)