Two ways to send http requests in java: HTTPClient and CloseableHttpClient and understanding of some annotations of swagger interface

tags: java  interface

Two ways to send http requests in java: HTTPClient and CloseableHttpClient and understanding of some annotations of swagger interface

There are three ways to send http requests in java. In addition to the native connection method HttpURLConnection, there are two other ways: HTTPClient and CloseableHttpClient
The following briefly introduces the methods of using HTTPClient and CloseableHTTPClient for Get and Post requests.
Use link for details

HttpClient
Using commons-httpclient.jar, maven depends on the following:

<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency>

The simple code is as follows:

private static String doGet(String url) {
    String res = null;
    HttpClient client = new HttpClient();
    GetMethod getMethod = new GetMethod(url);
    int code = 0;
    try {
        code = client.executeMethod(getMethod);
        if (code == 200) {
            res = getMethod.getResponseBodyAsString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return res;
}

private static String doPost(String url, Map<String, Object> paramMap) {
    String res = null;
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    postMethod.getParams().setContentCharset("UTF-8");
    Iterator<Map.Entry<String, Object>> iterator = paramMap.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, Object> next = iterator.next();
        postMethod.addParameter(next.getKey(), next.getValue().toString());
    }
    try {
        int code = client.executeMethod(postMethod);
        if (code == 200) {
            res = postMethod.getResponseBodyAsString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return res;
}

public static void main(String[] args) {
    //get
    System.out.println(doGet("http://localhost:8080/hello"));

    //post
    //Set the format of the incoming parameters: request parameters are in the form of map
    Map<String, Object> paramMap = new HashMap<>(2);
    paramMap.put("name", "Zhao Yun");
    paramMap.put("age", 21);
    System.out.println(doPost("http://localhost:8080/hello1", paramMap));
}

Called method:

Test Results:


CloseableHttpClient
Using httpclient.jar, maven depends on the following:

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>

The simple code is as follows:

/**
   * Send HttpGet request
 * @param url
 * @return
 */
public static String doGet(String url) {
    //1. Get an httpclient object
    CloseableHttpClient httpclient = HttpClients.createDefault();
    //2. Generate a get request
    HttpGet httpget = new HttpGet(url);
    CloseableHttpResponse response = null;
    try {
        //3. Execute the get request and return the result
        response = httpclient.execute(httpget);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    String result = null;
    try {
        //4. Processing the result, here the result is returned as a string
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            result = EntityUtils.toString(entity);
        }
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return result;
}

/**
   * Send HttpPost request, the parameter is map
 * @param url
 * @param map
 * @return
 */
public static String doPost(String url, Map<String, Object> map) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        //Assign a value to the parameter
        formparams.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
    }
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(entity);
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httppost);
    } catch (IOException e) {
        e.printStackTrace();
    }
    HttpEntity entity1 = response.getEntity();
    String result = null;
    try {
        result = EntityUtils.toString(entity1);
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    }
    return result;
}

public static void main(String[] args) {
    //get
    System.out.println(doGet("http://localhost:8080/hello"));

    //post
    //Set the format of the incoming parameters: request parameters are in the form of map
    Map<String, Object> paramMap = new HashMap<>(2);
    paramMap.put("name", "Zhang Fei");
    paramMap.put("age", 55);
    System.out.println(doPost("http://localhost:8080/hello1", paramMap));
}

Called method:

Test Results:


Swagger is currently the best open source project generated by Restful API documentation. Through the swagger-spring project, the seamless integration function of the springMVC framework is realized to facilitate the generation of restful style interface documents.

At the same time, swagger-ui can also test spring restful style interface functions

Scope of action API utilized location
Object attributes @ApiModelProperty Used on the field of the parameter object
Protocol set description @Api Used on Conntroller class
Protocol description @ApiOperation Used in the controller method
Response set @ApiResponses Used in the controller method
Response @ApiResponse Used in @ApiResponses
Non-object parameter set @ApilmplicitParams Used in the controller method
Non-object parameter description @ApiImplicitParam Used in the @ApiImplicitParams method
Describe the meaning of the returned object @ApiModel Used in the return object class

@Api: Used on the requested class to indicate the description of the class
tags = "Describe the function of this class, the annotation that can be seen on the UI interface"
value="This parameter is meaningless and can be seen on the UI interface, so no configuration is required"

@ApiOperation: Used on the requested method to explain the purpose and function of the method
value="Describe the purpose and function of the method"
notes="Method Notes"

@ApiImplicitParams: used in the request method, representing a set of parameter descriptions
@ApiImplicitParam: Used in the @ApiImplicitParams annotation to specify all aspects of a request parameter
name: parameter name
value: Chinese character description and explanation of the parameter
required: whether the parameter must be passed
paramType: where to put the parameter
· Header --> Get request parameters: @RequestHeader
· Query --> Get request parameters: @RequestParam
· Path (used for restful interface) -> get request parameters: @PathVariable
· Body (not commonly used)
· Form (not commonly used)
dataType: parameter type, default String, other values ​​dataType="Integer"
defaultValue: the default value of the parameter

@ApiResponses: used in the request method to represent a set of responses
@ApiResponse: Used in @ApiResponses, generally used to express an incorrect response message
code: number, such as 400
message: information, such as "request parameters are not filled in"
response: the class that threw the exception

@ApiModel: used on the response class to indicate a message that returns response data
(This is generally used when creating a post, using scenarios like @RequestBody,
When the request parameter cannot be described using @ApiImplicitParam annotation)
@ApiModelProperty: Used on properties to describe the properties of the response class

Intelligent Recommendation

Java sends several ways to send HTTP requests

Java sends several ways to send HTTP requests The following four methods of sending GET and POST requests: First type:HttpURLConnection、 Second type:URLConnection、 Third:HttpClient, HTTPClient often u...

Several ways of Java send HTTP requests

refer to: https://www.jb51.net/article/206762.htm java to send HTTP requests to send HTTP requests (mainly native+dependence) https://zhuanlan.zhihu.com/p/364017444 httpclient https://blog.csdn.net/it...

HttpClient CloseableHttpClient GetMethod PostMethod http

pom dependency HttpClient's get request method Idea running results: Postman debugging results: HttpClient's post request method Idea running results: Post request result: Get request method of Closea...

Java implements HttpClient to send GET and POST requests (https, http)

Java implements HttpClient to send GET and POST requests (https, http) 1, the introduction of related dependencies Jar package download:httpcore4.5.5.jar    fastjson-1.2.47.jar maven: 2...

JAVA uses httpclient to send common HTTP POST and GET requests

In the JAVA project development, it is inevitable to send an http request. The http request has a get post request. The following is an HTTP send request tool class that is organized by itself. Maven ...

More Recommendation

Java uses HttpClient to send http (get, post) requests

1. Add dependency in maven project pom.xml   <dependency>    <groupId>org.apache.httpcomponents</groupId>    <artifactId>httpclient</artifactId>    <version>4.5.8&l...

Two common methods for Java send HTTP requests

This article mainly introduces two common methods to send HTTP requests in Java program: JDK native httpurlConnection sends an HTTP request Apache HhttpClient Send HTTP request Both methods can send H...

(1) Python sending two ways to send HTTP requests (get and post)

Introduce the requests package Note: Send requests (including request lines, method types, heads, and physical) & common request methods include GET, POST, PUT, Delete 1. Send GET request Format: ...

Use Apache's HttpClient to send Http requests

Use Apache's HttpClient to send Http requests 1 Basic concepts 1.1 The difference between HttpClient, TCP/IP and Socket HttpClient is an open source project in Apache. It implements all the functions ...

Java sends HTTP requests with HTTPCLIENT

HttpClient is a subproject under Apache Jakarta Common, which is used to provide efficient, newest, feature-rich client programming kits that support HTTP protocols, encapsulate HTTPCLIENT into a tool...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top