[Utility class/method] -- HTTP interface call request through HttpClient in Java [Difficulty★★★]

In the self-developed Java backend system, it is often necessary to use a third-party Http interface call or to resolve a cross-domain http interface request, first use your own Java backend service to call the remote interface, obtain the data, and then Then make an Ajax call to the front end of your own system. The key technology here is Java's access to the Http interface. Generally, if it is just a simple application, we can use HttpClient to assist in the development.
For projects with Maven architecture, the following content can be added to the pom.xml file:
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.3</version>
</dependency>

If it is a self-built Java Web project, you need to import the relevant HttpClient jar package, you can go to the Http component page of the Apache official website to download:
http://hc.apache.org/downloads.cgi
or use Tsinghua University Mirror file:
http://mirrors.tuna.tsinghua.edu.cn/apache//httpcomponents/httpclient/binary/httpcomponents-client-4.5.3-bin.zip

After adding these Jar packages to the project, you can Use HttpClient too.

The reference code is as follows:

public class HttpClientUtil {
     public static String server_addr = "http://localhost:8080/Server-api-simulator";
     public static boolean notifyServerJobStateChanged(String jobName, String jobGroup, String state, String triggerIds){
   
     CloseableHttpClient httpclient = HttpClients.createDefault();  
     HttpPost httpPost = new HttpPost(server_addr + "/UpdateReqJobStateSvlt");
     System.out.println(server_addr + "/UpdateReqJobStateSvlt");
     List<NameValuePair> nvps = new ArrayList<NameValuePair>(); 
     nvps.add(new BasicNameValuePair("jobName", jobName)); 
     nvps.add(new BasicNameValuePair("jobGroup", jobGroup));
     nvps.add(new BasicNameValuePair("state", state));
     nvps.add(new BasicNameValuePair("triggerIds", ""));
       
     try {
           httpPost.setEntity(new UrlEncodedFormEntity(nvps));
           httpclient.execute(httpPost); 
     } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
     } catch (ClientProtocolException e) {
          e.printStackTrace();
     } catch (IOException e) {
         e.printStackTrace();
     } 
         return true;
     }
  
     public static void main(String[] args){
         notifyServerJobStateChanged("AAA", "BBB", "WAITING", "");
     }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326665223&siteId=291194637