Use HttpClient to call http post/get methods, and use dom4j to parse xml

Source: Internet
Author: User

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. extends entexception; import org. dom4j. export enthelper; 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 Docum EntException {String xml = request. getParameter ("xml"); String signature = request. getParameter ("signature "); // ************************* http client ************ * ****** // PostMethod postMethod = null; try {// construct the HttpClient instance HttpClient httpClient = new HttpClient (); // set the connection timeout to httpClient. getHttpConnectionManager (). getParams (). setConnectionTimeout (10000); // sets the character set httpClient. getParams (). setParameter (HttpMethod Params. HTTP_CONTENT_CHARSET, "UTF-8"); // create the POST Method Instance postMethod = new PostMethod (SERVER_URL ); // use the default recovery policy provided by the system. This policy automatically retries three times when an IO exception occurs. PostMethod. getParams (). setParameter (HttpMethodParams. SO_TIMEOUT, 20000); // retry the postMethod in case of an exception. getParams (). setParameter (HttpMethodParams. RETRY_HANDLER, new handler (); // parameter NameValuePair [] nameValuePairs = new NameValuePair [2]; nameValuePairs [0] = new NameValuePair ("xml", xml ); nameValuePairs [1] = new NameValuePair ("signature", signature); // Add the parameter to the Request Method postMethod. setRequestBody (na MeValuePairs); // send connection int statusCode = httpClient.exe cuteMethod (postMethod); if (statusCode = HttpStatus. SC _ OK) {String result = postMethod. getResponseBodyAsString (); logger.info ("returned data 1:" + result); logger.info ("Character Set:" + postMethod. getResponseCharSet (); String rspXml = new String (postMethod. getResponseBody (), "UTF-8"); logger.info ("returned data 2:" + rspXml); Document document = incluenthelper. 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 e Rror. ", 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 ("An error occurred while reading the data returned from the transaction warehouse order. ", 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 ("Zhejiang"); 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 ));}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.