HttpClient uses CloseableHttpClient to send post requests

tags: httpClient

General steps for sending requests using HttpClient
(1) Create an HttpClient object.
(2) Create an instance of the request method and specify the request URL. If you need to send a GET request, create an HttpGet object; if you need to send a POST request, create an HttpPost object.
(3) If you need to send request parameters, you can call the setParams(HetpParams params) method of HttpGet to add request parameters; for HttpPost objects, you can call the setEntity(HttpEntity entity) method to Set the request parameters.
(4) Call the execute(HttpUriRequest request) of the HttpClient object to send the request. This method returns an HttpResponse.
(5) Call the getAllHeaders() and getHeaders(String name) methods of HttpResponse to get the response header of the server; call the getEntity() method of HttpResponse to get the HttpEntity object, which wraps The server's response content. The program can obtain the server's response content through this object.
(6) Release the connection. Regardless of whether the execution method is successful, the connection must be released

code show as below:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class HttpTest {

    protected static Logger logger = Logger.getLogger(HttpTest.class);
    //Request timeout time, this time defines the timeout time for socket to read data, that is, the time to wait after connecting to the server to obtaining response data from the server. If a timeout occurs, a SocketTimeoutException will be thrown.
    private static final int SOCKET_TIME_OUT = 60000;
         //Connection timeout time, this time defines the timeout time for establishing a connection with the server through the network, that is, the waiting time for the connection to the target URL after a connection in the connection pool is obtained. When a timeout occurs, a ConnectionTimeoutException will be thrown
    private static final int CONNECT_TIME_OUT = 60000;

    private static List<NameValuePair> createParam(Map<String, Object> param) {
                 //Create a NameValuePair array to store the parameters to be transmitted
        List<NameValuePair> nvps = new ArrayList <NameValuePair>();
        if(param != null) {
            for(String k : param.keySet()) {
                nvps.add(new BasicNameValuePair(k, param.get(k).toString()));
            }
        }
        return nvps;
    }

    /**
           * Send post request
           * @param url request address, such as http://www.baidu.com
           * @param param related parameters, simulated form submission
     * @return
     * @throws Exception 
     */
    public static String postForAPP(String url, String sMethod, Map<String, Object> param, Map<String, Object> headers) throws Exception {
                 //The current implementation class of the latest version of HttpClient is CloseableHttpClient
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        HttpEntity entity=null;
        try {
            if(param != null) {
                                 //Create the object of the Request, which is generally constructed with the target url, and the Request is generally configured with addHeader, setEntity, and setConfig
                HttpPost req = new HttpPost(url);
                entity=new UrlEncodedFormEntity(createParam(param), Consts.UTF_8);
                                 //setHeader, add header file
                Set<String> keys = headers.keySet();
                for (String key : keys) {
                    req.setHeader(key, headers.get(key).toString());
                }
                                 //setConfig, add configuration, such as setting request timeout, connection timeout
                RequestConfig reqConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();
                req.setConfig(reqConfig);
                                 //setEntity, add content
                req.setEntity(entity);
                                 //Execute the Request request, the response returned by the execute method of CloseableHttpClient is of type CloseableHttpResponse
                                 //The commonly used methods are getFirstHeader(String), getLastHeader(String), headerIterator(String) to obtain the iterator corresponding to a Header name, getAllHeaders(), getEntity, getStatus, etc.
                response = client.execute(req);
                entity =  response.getEntity();
                                 //Use the static method EntityUtils.toString() to convert HttpEntity into a string to prevent the data returned by the server from containing Chinese, so it is enough to specify the character set as utf-8 when converting
                String result= EntityUtils.toString(entity, "UTF-8");
                logger.error("-------------------------"+result+"-------------");
                if(response.getStatusLine().getStatusCode()==200){
                    logger.error(result+"-----------success------------------");
                    return result;
                }else{
                    logger.error(response.getStatusLine().getStatusCode()+"------------------fail-----------");
                    return null;
                }
            }
            return null;
        } catch(Exception e) {
            logger.error("--------------------------post error: ", e);
            throw new Exception();
        }finally{
                         //Be sure to remember to fully consume the entity, otherwise the connection in the connection pool will always be occupied
            EntityUtils.consume(entity);
            logger.error("---------------------------finally-------------");
            System.out.println("---------------------------------------------------");
        }
    }


    public static void main(String[] args) throws Exception {
        Map<String, Object> param=new HashMap<String, Object>();
        param.put("pdata", "mm");
        Map<String, Object> headers=new HashMap<String, Object>();
        headers.put("appid", "mm");
        postForAPP("http://localhost:8080/SpringMVC-httpclient/greeting", "aa", param, headers);
    }

}

The project code will be uploaded later, the project name is SpringMVC-httpclient

Intelligent Recommendation

Java uses httpclient to send post, get, and delete requests

1. Httpclient Send POST 2. Httpclient Send GET 3. Httpclient Send Delete 1. Since HTTPDELETE cannot add parameters, you need to copy HTTPDELETE 2. Send delete request...

Send GET and POST requests with httpclient

Introduction The HTTP protocol may be the most useful, most important protocol on the Internet, more and more Java applications need to access network resources directly through the HTTP protocol. The...

Httpclient (6) -Send post requests ②

Use httpclient to send a most common post request, JSON format data request Code fragment is as follows Create an HTTP request client: httpclients.createDefault (), which is used to actually initiate ...

Httpclient (seven) -Send post requests ③

Use httpclient to send a post request containing attachment submission Create an HTTP request client: httpclients.createDefault (), which is used to actually initiate calling HTTP requests, which can ...

More Recommendation

Android uses HttpClient to send requests

I went to the interview these few days and was asked to write the code. All kinds of knowledge points are really forgotten.. So slowly write down some knowledge points. In fact, in android to send HTT...

JAVA uses HttpClient for POST requests

Specific code implementation reference URL: JAVA uses HttpClient for POST requests (HTTPS) by httpClient.getHostConfiguration().setHost(host, port, protocol); To set the host, port and protocol of the...

Two ways to send http requests in java: HTTPClient and CloseableHttpClient and understanding of some annotations of swagger 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...

Specific steps for httpclient to send GET and POST requests

The HttpClient method sends GET and POST requests to communicate with the background server: Here are just the steps you must go through to send a request using httpclient: Take the following code as ...

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

Top