CloseableHttpClient of http request method sent by Java

1. dependence

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.2</version>
</dependency>

2. Request steps

  • Use the help class HttpClients to create a CloseableHttpClient object
  • Create an HttpGet or HttpPost instance based on the type of HTTP request to send
  • Use the addHeader method to add request headers, such as user agent, accept encoding and other parameters
  • The common setParams(HetpParams params) method of HttpGet and HttpPost can be called to add request parameters; for HttpPost objects, the setEntity(HttpEntity entity) method can also be called to set request parameters.
  • Get CloseableHttpResponse instance by executing this HttpGet or HttpPost request
  • Get the status code, error information, response page and so on from the CloseableHttpResponse instance
  • Release the connection. The connection must be released whether or not the execution method succeeds

3. GET method

public void httpGet() {  
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        try {  
            // Create httpget    
            HttpGet httpget = new HttpGet("http://www.baidu.com/");  
            System.out.println("executing request " + httpget.getURI());  
            // Execute get request    
            CloseableHttpResponse response = httpclient.execute(httpget);  
            try {  
                // Get response entity    
                HttpEntity entity = response.getEntity();  
                // Print response status    
                System.out.println(response.getStatusLine());  
                if (entity != null) {  
                    // Print response content length    
                    System.out.println("Response content length: " + entity.getContentLength());  
                    // Print response content    
                    System.out.println("Response content: " + EntityUtils.toString(entity));  
                }  
            } finally {  
                response.close();  
            }  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (ParseException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            // Close connection, release resources    
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }

4. POST method

public static String httpPost(String host, int port, byte[] buf)
    {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {

            String url = "http://" + host + ":" + port;
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).build();//Set request and transfer timeout
            httpPost.setConfig(requestConfig);
            httpPost.addHeader("User-Agent", "Mozilla/5.0");

            ByteArrayEntity entity = new ByteArrayEntity(buf);
            httpPost.setEntity(entity);

            httpResponse = httpClient.execute(httpPost);

            reader = new BufferedReader(new InputStreamReader(
                    httpResponse.getEntity().getContent()));

            String inputLine;

            while ((inputLine = reader.readLine()) != null) {
                response.append(inputLine);
            }

        }catch (Exception var){
            var.printStackTrace();
        }finally {
            if(reader != null){
                reader.close();
            }
            if(httpResponse != null){
                httpResponse.close();
            }
            httpClient.close();
        }
        return response.toString();

    }

Tags: Programming Apache encoding

Posted on Mon, 04 Nov 2019 13:20:31 -0500 by seavers