Java-Using the client in WebService to invoke the three-party RESTAPI

Source: Internet
Author: User
Tags stub

Background

Recently, because of the requirements of the project, the remote WEBAPI (Restful format) is called in its own webservice. Your WebService program is written in Java code, so you need to implement a client in it to invoke the remote restful interface.

Selection

In fact, in their own projects there are similar calls, when using the "jaxrsclientfactory" to obtain static proxy client. Because this approach requires a WebService interface that relies on remote invocation (the need to introduce someone else's jar package). This creates a high coupling. therefore not applicable.

So it needs to be implemented in a low-coupling way. Then there is the idea of selection.

After searching online, the basic stereotypes are two ways:

1.HttpClient

2.RestTemplate

Next, we'll list the implementation codes for two different ways.

HttpClient
Importjava.io.IOException; ImportJava.text.MessageFormat; Importjava.util.ArrayList; Importjava.util.List; ImportJava.util.concurrent.TimeUnit; ImportOrg.apache.http.NameValuePair; Importorg.apache.http.client.ClientProtocolException; ImportOrg.apache.http.client.ResponseHandler; Importorg.apache.http.client.entity.UrlEncodedFormEntity; ImportOrg.apache.http.client.methods.HttpGet; ImportOrg.apache.http.client.methods.HttpPost; ImportOrg.apache.http.impl.client.BasicResponseHandler; Importorg.apache.http.impl.client.CloseableHttpClient; Importorg.apache.http.impl.client.HttpClients; ImportOrg.apache.http.message.BasicNameValuePair; ImportOrg.slf4j.Logger; Importorg.slf4j.LoggerFactory;  Public classHttpclientutil {Private Static FinalLogger log = Loggerfactory.getlogger (httpclientutil.class); PrivateCloseablehttpclient httpClient =Httpclients.createdefault ();  Public StaticString executepost (string url, string tdfBase64)throwsException {String result=NULL; HttpPost HttpPost=Newhttppost (URL); Httppost.setentity (NewHttpentity<string>(tdfBase64)); HttpResponse Response=Httpclient.execute (HttpPost); if(Response! =NULL) {httpentity resentity=response.getentity (); if(Resentity! =NULL) {result= Entityutils.tostring (resentity, "Utf-8"); }              }                    returnresult; }      }         Public Static voidMain (string[] args) {//TODO auto-generated Method StubString url = "Http://169.8.160.201:8080/xx/Webservice/Submit"; String BASE64TDF= "MS4WMTOXMZIDMS4WMJOWMJAXHTEUMDM6MR8WMR4YHZAWHTEUMDQ6SVJRHTEUMDU6MJAXNJA1MDQDMS4WNJOXHTEUMDC6Q09HRU5UHTEUMDG6VEHBSUXBTK qdms4wotptrvfvru5dru5pmtiznb0xljexoje5ljy5hteumti6mtkunjkcmi4wmde6mzedmi4wmdi6mdadmi4xnzy6mda3mda5ha== "; Httpclientutil Client=NewHttpclientutil (); String result=client.executepost (URL, BASE64TDF, ""));    SYSTEM.OUT.PRINTLN (result); }

Resttemplate
 Packagecom.biolive.client;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importorg.springframework.http.HttpEntity;Importorg.springframework.http.client.SimpleClientHttpRequestFactory;Importorg.springframework.web.client.RestClientException;Importorg.springframework.web.client.RestTemplate; Public classresttemplateclient {Private Static FinalLogger log = Loggerfactory.getlogger (resttemplateclient.class); Private Static Final intConnecttimeout= 5000; Private Static Final intreadtimeout=5000; Privateresttemplate resttemplate;  Publicresttemplateclient () {simpleclienthttprequestfactory requestfactory=Newsimpleclienthttprequestfactory ();        Requestfactory.setconnecttimeout (ConnectTimeout);                Requestfactory.setreadtimeout (readtimeout); Resttemplate=Newresttemplate (requestfactory); }         Publicstring executepost (string url, String base64tdf) {string result=NULL; Resttemplate=Newresttemplate (); Httpentity<string>request =NewHttpentity<string>(BASE64TDF); Try{result=resttemplate.postforobject (URL, request, String.class); }Catch(Restclientexception ex) {ex.printstacktrace (); Log.info ("Call Post Interface error:" +ex.getmessage ()); }                    returnresult; }     Public Static voidMain (string[] args) {//TODO auto-generated Method StubString url = "Http://169.8.160.201:8080/xx/Webservice/Submit"; String BASE64TDF= "MS4WMTOXMZIDMS4WMJOWMJAXHTEUMDM6MR8WMR4YHZAWHTEUMDQ6SVJRHTEUMDU6MJAXNJA1MDQDMS4WNJOXHTEUMDC6Q09HRU5UHTEUMDG6VEHBSUXBTK qdms4wotptrvfvru5dru5pmtiznb0xljexoje5ljy5hteumti6mtkunjkcmi4wmde6mzedmi4wmdi6mdadmi4xnzy6mda3mda5ha== "; Resttemplateclient Client=Newresttemplateclient (); String result=client.executepost (URL, BASE64TDF);    SYSTEM.OUT.PRINTLN (result); }        }

Summarize

First, there are two ways to accomplish a task with only the URL and method type (get/post/put/update), and the invocation is very similar. Resttemplate is the spring's official package and recommended client, and can be combined and configured to suit your needs and spring.

Use of appendix Resttemplate

The Resttemplate has two construction methods, namely:

public RestTemplate() {          /**               ...初始化过程          */} public RestTemplate(ClientHttpRequestFactory requestFactory) { this(); setRequestFactory(requestFactory);}

Where the second constructor can pass in the Clienthttprequestfactory parameter, the first is initialized by default, because we often need to set the request time-out and be able to process the timeout, and the first constructor, we can't control the time-out. The second constructed method has a timeout attribute in the implementation class of the Clienthttprequestfactory interface in the second construct.
In the spring configuration file, configure the following:

<!-- 配置RestTemplate -->         <!--Http client Factory-->          <bean id="httpClientFactory" class="org.springframework.http.client.SimpleClientHttpRequestFactory">              <property name="connectTimeout"  value="${connectTimeout}"/>            <property name="readTimeout" value="${readTimeout}"/> </bean> <!--RestTemplate--> <bean id="restTemplate" class="org.springframework.web.client.RestTemplate"> <constructor-arg ref="httpClientFactory"/> </bean>

Of course, you can use it directly:

        new SimpleClientHttpRequestFactory();        requestFactory.setConnectTimeout(1000);        requestFactory.setReadTimeout(1000);        RestTemplate restTemplate = new RestTemplate(requestFactory);

Note: The Clienthttprequestfactory interface has 4 implementation classes, namely:

    • Abstractclienthttprequestfactorywrapper the abstract class used to assemble other request factory.
    • Commonsclienthttprequestfactory allows users to configure httpclient with authentication and HTTP connection pooling, deprecated, httpcomponentsclienthttprequestfactory recommended.
    • Httpcomponentsclienthttprequestfactory with 2.
    • A simple implementation of the Simpleclienthttprequestfactory interface, configurable parameters such as Proxy,connecttimeout,readtimeout
Reference

Http://www.cnblogs.com/softidea/p/5977375.html

http://blog.csdn.net/zpf336/article/details/73480810

Java-Using the client in WebService to invoke the three-party RESTAPI

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.