Two ways to send http requests in java: HTTPClient and CloseableHttpClient

tags: Http  Java  

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 to make 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 result:

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. Obtain 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 result:

Intelligent Recommendation

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 ...

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...

More Recommendation

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...

HTTPCLIENT sent by HTTP requests in Java

HTTPCLIENT sent by HTTP requests in Java 1 Introduction to HTTPClient 2 HTTPCLIENT case The HTTP protocol is one of the most used and most important protocols on the Internet. More and more Java appli...

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

Top