In daily work, we often need to connect with third-party systems. As clients, we call their interfaces for business processing
Several commonly used calls are:
- 1. Native (jdk);
- 2. Re-encapsulated HttpClient and CloseableHttpClient (Apache);
- RestTemplate provided;
Of course, there are interfaces for encapsulation of other tool classes, such as hutool's HttpUtil tool class. In addition to post and get requests, there are also methods for downloading files, downloadFile, etc.
HttpURLConnection calling method
The content of the HTTP body is written through the OutputStream stream. The data written to the stream will not be sent to the network immediately, but exists in the memory buffer. When the stream is closed, the HTTP body is generated based on the written content.
When the getInputStream() method is called, an input stream will be returned, which is used to read the server's return message for HTTP requests.
@Slf4j public class HttpURLConnectionUtil { /** * * Description: Send http request to send post and json formats * @param url Request URL * @param params json format request parameters */ public static String doPost(String url, String params) throws Exception { OutputStreamWriter out = null; BufferedReader reader = null; StringBuffer response = new StringBuffer(); URL httpUrl = null; // HTTP URL class Use this class to create a connection try { // Create URL httpUrl = new URL(url); ("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + url + "---------params:" + params); // Create a connection HttpURLConnection conn = (HttpURLConnection) (); //The method of setting the request is "POST", the default is GET ("POST"); ("Content-Type", "application/json"); ("connection", "keep-alive"); (false);// Settings do not cache (true); // Since URLConnection does not allow output by default, setDoOutput(true) must be called before requesting the output stream. (true); // Set whether to read from httpUrlConnection (true); //Set the timeout time (30000); (30000); (); // POST request out = new OutputStreamWriter(()); (params); (); // Read the response reader = new BufferedReader(new InputStreamReader((), "utf-8")); String lines; while ((lines = ()) != null) { (lines); } (); // Disconnect (); } catch (Exception e) { ("--------StartHttp Post ask abnormal {}-------------", e); throw new Exception(e); } // Use finally blocks to close the output stream and input stream finally { try { if (out != null) { (); } if (reader != null) { (); } } catch (IOException ex) { ((ex)); } } return (); } }
CloseableHttpClient call
CloseableHttpClient is an abstract class that implements the httpClient interface and also implements it;
Supports connection pool management, reuses established connections PoolingHttpClientConnectionManager
Automatically manage connection release via ()
Support HTTPS access HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
@Slf4j public class CloseableHttpClientUtil { /** *url Third-party interface address *json The incoming message style can be a dto object, string, json, etc. *header Additional incoming request header parameters */ public static String doPost(String url, Object json,Map<String,String> header) { CloseableHttpClient httpclient = ().build(); HttpPost httpPost= new HttpPost(url);//Post request type String result="";//Return result String requestJson="";//Send message body try { requestJson=(json); ("Send address:"+url+"Send message:"+requestJson); //StringEntity s = new StringEntity(requestJson, ("UTF-8")); StringEntity s= new StringEntity(requestJson, "UTF-8"); // The post request is to place the parameters in the request body and pass it over; here the entity is placed in the post request body ("Content-Type", "application/json;charset=utf8"); (s); if(header!=null){ Set<String> strings = (); for(String str:strings){ (str,(str)); } } HttpResponse res = (httpPost); if (().getStatusCode() == HttpStatus.SC_OK) { result = (()); //You can also convert the returned packet into json type // JSONObject response = (result); } } catch (Exception e) { throw new RuntimeException(e); } finally { // Here you can add a logging method // Close the connection and release the resources if (httpclient!= null){ try { (); } catch (IOException e) { (); } } } return result; } }
RestTemplate call
//You can add RestTemplate beans to the project startup class, and you can then introduce them in the code @Autowired.@Bean public RestTemplate restTemplate() { return new RestTemplate(); }
@Slf4j @Component public class RestTemplateUtils { @Autowired private RestTemplate restTemplate; /** * get request parameter is after url http://xxxx?aa=xxx&page=0&size=10"; * @param urls * @return string */ public String doGetRequest(String urls) { URI uri = (urls).build().toUri(); ("Request interface:{}", urls); HttpHeaders headers = new HttpHeaders(); (MediaType.APPLICATION_JSON); HttpEntity<String> httpEntity = new HttpEntity<>(headers); //Universal method exchange, this method requires you to specify the request type when calling, which can be get, post, or other types of requests. ResponseEntity<String> responseEntity = (uri, , httpEntity, ); if (responseEntity == null) { return null; } ("Return to the message:{}", (responseEntity)); return (); } /** * post request parameter is in request; * @param url, request * @return string */ public String doPostRequest(String url, Object request){ URI uri = (url).build().toUri(); String requestStr= (request); ("Request interface:{}, Request message:{}", url, requestStr); HttpHeaders headers = new HttpHeaders(); (MediaType.APPLICATION_JSON); HttpEntity<String> httpEntity = new HttpEntity<>(requestStr, headers); ResponseEntity<String> responseEntity = (uri, , httpEntity, ); if (responseEntity == null) { return null; } String seqResult = ""; try { if(() != null ) { if(().contains("9001")) { seqResult = new String(().getBytes("ISO8859-1"),"utf-8"); }else { seqResult = new String(().getBytes(),"utf-8"); } } ("Return to the message:{}", seqResult); } catch (UnsupportedEncodingException e) { ("Interface returns exception", e); } return seqResult; } }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.