HttpClient和RestTemplate简单总结

HttpClient和RestTemplate简单总结

HttpClient:

自我感觉应用定义繁琐

	/**
	 * 
	 * @param bean 参数bean
	 * @param ipAndPort 远程调用的ip和端口
	 * @param path 接口路径
	 * @author zs
	 * @return
	 */
	@SuppressWarnings("unused")
	public static String HttpClientPost(JSONObject bean,String ipAndPort,String path) {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String returnBody = null;
		//设置超时时间
		RequestConfig requestConfig = RequestConfig.custom()
				.setConnectTimeout(6000)//设置连接超时时间,单位毫秒 6000s
				.setSocketTimeout(6000) //请求获取数据的超时时间,单位毫秒 6000s
				.setConnectionRequestTimeout(1000)//1000s,设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。    
				//.setStaleConnectionCheckEnabled(true)
				.setRedirectsEnabled(false)//不允许允许自动重定向
				.build();
		httpClient = HttpClients.custom()
				.setDefaultRequestConfig(requestConfig)
				.build();

		HttpPost httpPost = new HttpPost(ipAndPort+path);
		log.info("ip和端口>>>>"+ipAndPort);
		httpPost.addHeader("Content-type","application/json; charset=utf-8");
		httpPost.setHeader("Accept", "application/json");
		StringEntity content = new StringEntity(bean.toString(),Charset.forName("utf-8"));
		httpPost.setEntity(content); 
		try {
			response = httpClient.execute(httpPost);
			entity = response.getEntity();
			if (entity != null) {
				returnBody = EntityUtils.toString(entity, "utf-8");
				log.info("查询远程接口返回信息>>>>"+returnBody);
			}else{
				log.info("返回数据为空,请联系管理员查看端口启用情况>>>>>>");
			}
		} catch (ConnectTimeoutException e) {
			String trace = "HttpClient远程调用接口异常:"+e.getMessage();
			log.error(trace,e);
		} catch (Exception e) {
			String trace = "HttpClient远程调用接口异常:"+e.getMessage();
			log.error(trace,e);
		}
		return returnBody;
	}

RestTemplate:

代码逻辑简单,几行代码就能搞定
定义相应头:

//定义请求头,用来封装HttpEntity
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

封转参数bean,执行远程调用接口

HttpEntity<Object> entity = new HttpEntity<Object>(bean, headers);
        Object object = restTemplate.postForObject(url, entity, Object.class);

你可能感兴趣的:(HttpClient和RestTemplate简单总结)