HttpClient tools, 2021 Tencent Java advanced interview questions and answers

/**

 * Send get request; With request parameters

 * 

 * @param url Request address

 * @param params Request parameter set

 * @return

 * @throws Exception

 */

public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {

	return doGet(url, null, params);

}



/**

 * Send get request; With request header and request parameters

 * 

 * @param url Request address

 * @param headers Request header set

 * @param params Request parameter set

 * @return

 * @throws Exception

 */

public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {

	// Create httpClient object

	CloseableHttpClient httpClient = HttpClients.createDefault();



	// Create access address

	URIBuilder uriBuilder = new URIBuilder(url);

	if (params != null) {

		Set<Entry<String, String>> entrySet = params.entrySet();

		for (Entry<String, String> entry : entrySet) {

			uriBuilder.setParameter(entry.getKey(), entry.getValue());

		}

	}



	// Create http object

	HttpGet httpGet = new HttpGet(uriBuilder.build());

	/**

	 * setConnectTimeout: Sets the connection timeout in milliseconds.

	 * setConnectionRequestTimeout: Set to get a Connection from the connect manager

	 * Timeout in milliseconds. This attribute is a new attribute, because the current version can share the connection pool.

	 * setSocketTimeout: The timeout (i.e. response time) of the request to obtain data, in milliseconds. If you access an interface and cannot return data for how long, you can directly give up the call.

	 */

	RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();

	httpGet.setConfig(requestConfig);

	

	// Set request header

	packageHeader(headers, httpGet);



	// Create httpResponse object

	CloseableHttpResponse httpResponse = null;



	try {

		// Execute the request and get the response result

		return getHttpClientResult(httpResponse, httpClient, httpGet);

	} finally {

		// Release resources

		release(httpResponse, httpClient);

	}

}



/**

 * Send a post request; Without request header and request parameters

 * 

 * @param url Request address

 * @return

 * @throws Exception

 */

public static HttpClientResult doPost(String url) throws Exception {

	return doPost(url, null, null);

}



/**

 * Send a post request; With request parameters

 * 

 * @param url Request address

 * @param params Parameter set

 * @return

 * @throws Exception

 */

public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {

	return doPost(url, null, params);

}



/**

 * Send a post request; With request header and request parameters

 * 

 * @param url Request address

 * @param headers Request header set

 * @param params Request parameter set

 * @return

 * @throws Exception

 */

public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {

	// Create httpClient object

	CloseableHttpClient httpClient = HttpClients.createDefault();



	// Create http object

	HttpPost httpPost = new HttpPost(url);

	/**

	 * setConnectTimeout: Sets the connection timeout in milliseconds.

	 * setConnectionRequestTimeout: Set to get a Connection from the connect manager

	 * Timeout in milliseconds. This attribute is a new attribute, because the current version can share the connection pool.

	 * setSocketTimeout: The timeout (i.e. response time) of the request to obtain data, in milliseconds. If you access an interface and cannot return data for how long, you can directly give up the call.

	 */

	RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();

	httpPost.setConfig(requestConfig);

	// Set request header

	/*httpPost.setHeader("Cookie", "");

	httpPost.setHeader("Connection", "keep-alive");

	httpPost.setHeader("Accept", "application/json");

	httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");

	httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");

	httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/

	packageHeader(headers, httpPost);

	

	// Encapsulation request parameters

	packageParam(params, httpPost);



	// Create httpResponse object

	CloseableHttpResponse httpResponse = null;



	try {

		// Execute the request and get the response result

		return getHttpClientResult(httpResponse, httpClient, httpPost);

	} finally {

		// Release resources

		release(httpResponse, httpClient);

	}

}



/**

 * Send put request; Without request parameters

 * 

 * @param url Request address

 * @param params Parameter set

 * @return

 * @throws Exception

 */

public static HttpClientResult doPut(String url) throws Exception {

	return doPut(url);

}



/**

 * Send put request; With request parameters

 * 

 * @param url Request address

 * @param params Parameter set

 * @return

 * @throws Exception

 */

public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception {

	CloseableHttpClient httpClient = HttpClients.createDefault();

	HttpPut httpPut = new HttpPut(url);

	RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();

	httpPut.setConfig(requestConfig);

	

	packageParam(params, httpPut);



	CloseableHttpResponse httpResponse = null;



	try {

		return getHttpClientResult(httpResponse, httpClient, httpPut);

	} finally {

		release(httpResponse, httpClient);

	}

}



/**

 * Send delete request; Without request parameters

 * 

 * @param url Request address

 * @param params Parameter set

 * @return

 * @throws Exception

 */

public static HttpClientResult doDelete(String url) throws Exception {

	CloseableHttpClient httpClient = HttpClients.createDefault();

	HttpDelete httpDelete = new HttpDelete(url);

	RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();

	httpDelete.setConfig(requestConfig);



	CloseableHttpResponse httpResponse = null;

	try {

		return getHttpClientResult(httpResponse, httpClient, httpDelete);

	} finally {

		release(httpResponse, httpClient);

	}

}



/**

 * Send delete request; With request parameters

 * 

 * @param url Request address

 * @param params Parameter set

 * @return

 * @throws Exception

 */

public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception {

	if (params == null) {

		params = new HashMap<String, String>();

	}



	params.put("_method", "delete");

	return doPost(url, params);

}



/**

 * Description: Encapsulation request header

 * @param params

 * @param httpMethod

 */

public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {

	// Encapsulation request header

	if (params != null) {

		Set<Entry<String, String>> entrySet = params.entrySet();

		for (Entry<String, String> entry : entrySet) {

			// Set to request header into HttpRequestBase object

			httpMethod.setHeader(entry.getKey(), entry.getValue());

		}

	}

}



/**

 * Description: Encapsulation request parameters

 * 

 * @param params

 * @param httpMethod

 * @throws UnsupportedEncodingException

 */

public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)

		throws UnsupportedEncodingException {

	// Encapsulation request parameters

	if (params != null) {

		List<NameValuePair> nvps = new ArrayList<NameValuePair>();

		Set<Entry<String, String>> entrySet = params.entrySet();

		for (Entry<String, String> entry : entrySet) {

			nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));

		}



		// Set to the requested http object

		httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));

	}

}



/**

 * Description: Get response results

 * 

 * @param httpResponse

 * @param httpClient

 * @param httpMethod

 * @return

 * @throws Exception

 */

public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,

		CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {

	// Execute request

	httpResponse = httpClient.execute(httpMethod);



	// Get return result

	if (httpResponse != null && httpResponse.getStatusLine() != null) {

		String content = "";

		if (httpResponse.getEntity() != null) {

			content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);

		}

		return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);

	}

	return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);

}



/**

 * Description: Release resources

 * 

 * @param httpResponse

 * @param httpClient

 * @throws IOException

 */

public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {

	// Release resources

	if (httpResponse != null) {

		httpResponse.close();

	}

	if (httpClient != null) {

		httpClient.close();

	}

}

}



### [] () 6.6 start spring boot and test get and post requests



/**

  • Description: HttpClientUtils tool class test

  • @author JourWon

  • @Date created on April 19, 2018

*/

public class HttpClientUtilsTest {

/**

 * Description: Test get no parameter request

 * 

 * @throws Exception

 */

@Test

public void testGet() throws Exception {

	HttpClientResult result = HttpClientUtils.doGet("http://127.0.0.1:8080/hello/get");

	System.out.println(result);

}



/**

 * Description: Test get with parameter request

 * 

 * @throws Exception

 */

@Test

public void testGetWithParam() throws Exception {

	Map<String, String> params = new HashMap<String, String>();

	params.put("message", "helloworld");

	HttpClientResult result = HttpClientUtils.doGet("http://127.0.0.1:8080/hello/getWithParam", params);

	System.out.println(result);

}



/**

 * Description: Test post with request header without request parameters

 * 

 * @throws Exception

 */

@Test

public void testPost() throws Exception {

	Map<String, String> headers = new HashMap<String, String>();

	headers.put("Cookie", "123");

	headers.put("Connection", "keep-alive");

	headers.put("Accept", "application/json");

	headers.put("Accept-Language", "zh-CN,zh;q=0.9");

	headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");

	HttpClientResult result = HttpClientUtils.doPost("http://127.0.0.1:8080/hello/post", headers, null);

	System.out.println(result);

}



/**

 * Description: Test post with parameter request

 * 

 * @throws Exception

 */

@Test

public void testPostWithParam() throws Exception {

	Map<String, String> params = new HashMap<String, String>();

	params.put("code", "0");

	params.put("message", "helloworld");

	HttpClientResult result = HttpClientUtils.doPost("http://127.0.0.1:8080/hello/postWithParam", params);

Spring full set of teaching materials

Spring is the "sunflower dictionary" of Java programmers, which provides various great tricks that can simplify our development and greatly improve development efficiency! At present, 99% of companies use spring. You can go to major recruitment websites. Spring is a necessary skill, so you must master it.

CodeChina open source project: [analysis of Java interview questions of front-line large manufacturers + core summary learning notes + latest explanation Video]

catalog:

Some contents:

Spring source code

  • Part I overview of Spring
  • The second part is the core idea
  • The third part is the implementation of IoC and AOP (custom Spring framework)
  • Part IV advanced application of Spring IOC
    Basic characteristics
    Advanced features
  • The fifth part is the in-depth analysis of Spring IOC source code
    Elegant design
    Design pattern
    Note: principles, methods and techniques
  • Part VI Spring AOP application
    Declare transaction control
  • The seventh part is the in-depth analysis of Spring AOP source code
    Necessary notes, necessary drawings and easy to understand language to resolve knowledge difficulties

Scaffold framework: SpringBoot Technology

Its goal is to simplify the creation, development and deployment of Spring applications and services, simplify the configuration file, use embedded web server, contain many out of the box microservice functions, and can be jointly deployed with spring cloud.

The core idea of Spring Boot is that convention is greater than configuration. Applications only need a few configurations, which simplifies the application development mode.

  • Getting started with SpringBoot
  • configuration file
  • journal
  • Web development
  • Docker
  • SpringBoot and data access
  • Startup configuration principle
  • Custom starter

Microservice architecture: Spring Cloud Alibaba

Like Spring Cloud, Spring Cloud Alibaba is also a set of microservice solutions, including the necessary components for developing distributed application microservices, so that developers can easily use these components to develop distributed application services through the Spring Cloud programming model.

  • Introduction to microservice architecture
  • Introduction to Spring Cloud Alibaba
  • Microservice environment construction
  • Service governance
  • Service fault tolerance
  • Service gateway
  • Link tracking
  • ZipKin integration and data persistence
  • Message driven
  • SMS service
  • Nacos config - service configuration
  • Seata - distributed transactions
  • Dubbo rpc communication

Spring MVC

catalog:

Some contents:

Startup configuration principle

  • Custom starter

[external chain picture transferring... (img-3POCfnlA-1630816839423)]

[external chain picture transferring... (img-GsZgPR38-1630816839424)]

Microservice architecture: Spring Cloud Alibaba

Like Spring Cloud, Spring Cloud Alibaba is also a set of microservice solutions, including the necessary components for developing distributed application microservices, so that developers can easily use these components to develop distributed application services through the Spring Cloud programming model.

  • Introduction to microservice architecture
  • Introduction to Spring Cloud Alibaba
  • Microservice environment construction
  • Service governance
  • Service fault tolerance
  • Service gateway
  • Link tracking
  • ZipKin integration and data persistence
  • Message driven
  • SMS service
  • Nacos config - service configuration
  • Seata - distributed transactions
  • Dubbo rpc communication

[external chain picture transferring... (img-GWuP1cwb-1630816839424)]

[external chain picture transferring... (img-hVx6tilX-1630816839425)]

Spring MVC

catalog:

[external chain picture transferring... (img-dnn0iXfp-1630816839426)]

[external chain picture transferring... (IMG ygamkrbg-1630816839426)]

[external chain picture transferring... (img-SZ7gpf9A-1630816839427)]

Some contents:

[external chain picture transferring... (img-WspQDCv3-1630816839427)]

[external chain picture transferring... (img-TjdP4RgS-1630816839428)]

Keywords: Java Back-end Interview Programmer http

Added by krs10_s on Thu, 16 Dec 2021 07:13:17 +0200