From 6ce8d8ca79d058485ff74cd8b896a44237a3f1ea Mon Sep 17 00:00:00 2001 From: "mai.jh" Date: Mon, 22 Jun 2020 20:42:46 +0800 Subject: [PATCH] [ISSUE #3140]nacos-client module replace http client (#3142) * nacos-client http client replace * Remove some explain * Remove some explain * Adjust some code styles and fix some misspelled method names * Fix code style issues * fix some misspelled method names * Fix code style issues --- .../nacos/client/naming/net/HttpClient.java | 3 + .../naming/net/NamingHttpClientManager.java | 18 ++-- .../nacos/client/naming/net/NamingProxy.java | 84 +++++++++++-------- .../nacos/client/security/SecurityProxy.java | 46 +++++----- .../nacos/common/http/BaseHttpMethod.java | 2 +- .../common/http/HttpClientBeanHolder.java | 8 +- .../http/client/HttpClientResponse.java | 1 - .../http/client/NacosAsyncRestTemplate.java | 8 +- .../common/http/client/NacosRestTemplate.java | 31 +++++-- .../common/http/handler/ResponseHandler.java | 16 +++- .../common/NacosAsyncRestTemplate_ITCase.java | 8 +- .../test/common/NacosRestTemplate_ITCase.java | 8 +- .../naming/AutoDeregisterInstance_ITCase.java | 2 +- .../alibaba/nacos/test/naming/NamingBase.java | 45 +++++----- 14 files changed, 161 insertions(+), 119 deletions(-) diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java b/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java index 8fa1327ff8a..6d95c40d582 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java @@ -16,6 +16,7 @@ package com.alibaba.nacos.client.naming.net; import com.alibaba.nacos.api.common.Constants; +import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.utils.HttpMethod; import com.alibaba.nacos.common.utils.IoUtils; import com.alibaba.nacos.common.utils.StringUtils; @@ -35,7 +36,9 @@ /** * @author nkorange + * @deprecated Use NacosRestTemplate{@link NacosRestTemplate} unified http client */ +@Deprecated public class HttpClient { public static final int READ_TIME_OUT_MILLIS = Integer diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingHttpClientManager.java b/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingHttpClientManager.java index 359ec9dff14..f38c64807a6 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingHttpClientManager.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingHttpClientManager.java @@ -16,17 +16,19 @@ package com.alibaba.nacos.client.naming.net; -import com.alibaba.nacos.common.http.*; +import com.alibaba.nacos.common.http.AbstractHttpClientFactory; +import com.alibaba.nacos.common.http.HttpClientBeanHolder; +import com.alibaba.nacos.common.http.HttpClientConfig; +import com.alibaba.nacos.common.http.HttpClientFactory; import com.alibaba.nacos.common.http.client.NacosRestTemplate; /** * http Manager * * @author mai.jh - * @date 2020/6/14 */ public class NamingHttpClientManager { - + private static final int READ_TIME_OUT_MILLIS = Integer .getInteger("com.alibaba.nacos.client.naming.rtimeout", 50000); private static final int CON_TIME_OUT_MILLIS = Integer @@ -34,22 +36,22 @@ public class NamingHttpClientManager { private static final boolean ENABLE_HTTPS = Boolean .getBoolean("com.alibaba.nacos.client.naming.tls.enable"); private static final int MAX_REDIRECTS = 5; - + private static final HttpClientFactory HTTP_CLIENT_FACTORY = new NamingHttpClientFactory(); - + public static String getPrefix() { if (ENABLE_HTTPS) { return "https://"; } return "http://"; } - + public static NacosRestTemplate getNacosRestTemplate() { return HttpClientBeanHolder.getNacosRestTemplate(HTTP_CLIENT_FACTORY); } - + private static class NamingHttpClientFactory extends AbstractHttpClientFactory { - + @Override protected HttpClientConfig buildHttpClientConfig() { return HttpClientConfig.builder() diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java b/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java index 07a7603b8dc..ec2f7d248af 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/net/NamingProxy.java @@ -37,15 +37,19 @@ import com.alibaba.nacos.client.utils.AppNameUtils; import com.alibaba.nacos.client.utils.TemplateUtils; import com.alibaba.nacos.common.constant.HttpHeaderConsts; +import com.alibaba.nacos.common.http.HttpRestResult; +import com.alibaba.nacos.common.http.client.NacosRestTemplate; +import com.alibaba.nacos.common.http.param.Header; +import com.alibaba.nacos.common.http.param.Query; import com.alibaba.nacos.common.lifecycle.Closeable; import com.alibaba.nacos.common.utils.*; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; +import org.apache.http.HttpStatus; import java.io.IOException; import java.io.StringReader; import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; @@ -53,6 +57,7 @@ import java.util.Properties; import java.util.Map; import java.util.HashMap; +import java.util.Collections; import java.util.Random; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; @@ -67,6 +72,8 @@ */ public class NamingProxy implements Closeable { + private NacosRestTemplate nacosRestTemplate = NamingHttpClientManager.getNacosRestTemplate(); + private static final int DEFAULT_SERVER_PORT = 8848; private int serverPort = DEFAULT_SERVER_PORT; @@ -144,15 +151,14 @@ public List getServerListFromEndpoint() { try { String urlString = "http://" + endpoint + "/nacos/serverlist"; - List headers = builderHeaders(); - - HttpClient.HttpResult result = HttpClient.httpGet(urlString, headers, null, UtilAndComs.ENCODING); - if (HttpURLConnection.HTTP_OK != result.code) { + Header header = builderHeader(); + HttpRestResult restResult = nacosRestTemplate.get(urlString, header, Query.EMPTY, String.class); + if (!restResult.ok()) { throw new IOException("Error while requesting: " + urlString + "'. Server returned: " - + result.code); + + restResult.getCode()); } - String content = result.content; + String content = restResult.getData(); List list = new ArrayList(); for (String line : IoUtils.readLines(new StringReader(content))) { if (!line.trim().isEmpty()) { @@ -333,10 +339,10 @@ public JsonNode sendBeat(BeatInfo beatInfo, boolean lightBeatEnabled) throws Nac NAMING_LOGGER.debug("[BEAT] {} sending beat to server: {}", namespaceId, beatInfo.toString()); } Map params = new HashMap(8); - String body = StringUtils.EMPTY; + Map bodyMap = new HashMap(2); if (!lightBeatEnabled) { try { - body = "beat=" + URLEncoder.encode(JacksonUtils.toJson(beatInfo), "UTF-8"); + bodyMap.put("beat", URLEncoder.encode(JacksonUtils.toJson(beatInfo), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new NacosException(NacosException.SERVER_ERROR, "encode beatInfo error", e); } @@ -346,7 +352,7 @@ public JsonNode sendBeat(BeatInfo beatInfo, boolean lightBeatEnabled) throws Nac params.put(CommonParams.CLUSTER_NAME, beatInfo.getCluster()); params.put("ip", beatInfo.getIp()); params.put("port", String.valueOf(beatInfo.getPort())); - String result = reqAPI(UtilAndComs.NACOS_URL_BASE + "/instance/beat", params, body, HttpMethod.PUT); + String result = reqAPI(UtilAndComs.NACOS_URL_BASE + "/instance/beat", params, bodyMap, HttpMethod.PUT); return JacksonUtils.toObj(result); } @@ -399,10 +405,10 @@ public ListView getServiceList(int pageNo, int pageSize, String groupNam } public String reqAPI(String api, Map params, String method) throws NacosException { - return reqAPI(api, params, StringUtils.EMPTY, method); + return reqAPI(api, params, Collections.EMPTY_MAP, method); } - public String reqAPI(String api, Map params, String body, String method) throws NacosException { + public String reqAPI(String api, Map params, Map body, String method) throws NacosException { return reqAPI(api, params, body, getServerList(), method); } @@ -414,16 +420,16 @@ private List getServerList() { return snapshot; } - public String callServer(String api, Map params, String body, String curServer) throws NacosException { + public String callServer(String api, Map params, Map body, String curServer) throws NacosException { return callServer(api, params, body, curServer, HttpMethod.GET); } - public String callServer(String api, Map params, String body, String curServer, String method) + public String callServer(String api, Map params, Map body, String curServer, String method) throws NacosException { long start = System.currentTimeMillis(); long end = 0; injectSecurityInfo(params); - List headers = builderHeaders(); + Header header = builderHeader(); String url; if (curServer.startsWith(UtilAndComs.HTTPS) || curServer.startsWith(UtilAndComs.HTTP)) { @@ -432,27 +438,30 @@ public String callServer(String api, Map params, String body, St if (!curServer.contains(UtilAndComs.SERVER_ADDR_IP_SPLITER)) { curServer = curServer + UtilAndComs.SERVER_ADDR_IP_SPLITER + serverPort; } - url = HttpClient.getPrefix() + curServer + api; + url = NamingHttpClientManager.getPrefix() + curServer + api; } - HttpClient.HttpResult result = HttpClient.request(url, headers, params, body, UtilAndComs.ENCODING, method); - end = System.currentTimeMillis(); - - MetricsMonitor.getNamingRequestMonitor(method, url, String.valueOf(result.code)) - .observe(end - start); + try { + HttpRestResult restResult = nacosRestTemplate.exchangeForm(url, header, params, body, method, String.class); + end = System.currentTimeMillis(); - if (HttpURLConnection.HTTP_OK == result.code) { - return result.content; - } + MetricsMonitor.getNamingRequestMonitor(method, url, String.valueOf(restResult.getCode())) + .observe(end - start); - if (HttpURLConnection.HTTP_NOT_MODIFIED == result.code) { - return StringUtils.EMPTY; + if (restResult.ok()) { + return restResult.getData(); + } + if (HttpStatus.SC_NOT_MODIFIED == restResult.getCode()) { + return StringUtils.EMPTY; + } + throw new NacosException(restResult.getCode(), restResult.getData()); + } catch (Exception e) { + NAMING_LOGGER.error("[NA] failed to request", e); + throw new NacosException(NacosException.SERVER_ERROR, e); } - - throw new NacosException(result.code, result.content); } - public String reqAPI(String api, Map params, String body, List servers, String method) throws NacosException { + public String reqAPI(String api, Map params, Map body, List servers, String method) throws NacosException { params.put(CommonParams.NAMESPACE_ID, getNamespaceId()); @@ -526,14 +535,15 @@ private void injectSecurityInfo(Map params) { } } - public List builderHeaders() { - List headers = Arrays.asList( - HttpHeaderConsts.CLIENT_VERSION_HEADER, VersionUtils.version, - HttpHeaderConsts.USER_AGENT_HEADER, UtilAndComs.VERSION, - "Accept-Encoding", "gzip,deflate,sdch", - "Connection", "Keep-Alive", - "RequestId", UuidUtils.generateUuid(), "Request-Module", "Naming"); - return headers; + public Header builderHeader() { + Header header = Header.newInstance(); + header.addParam(HttpHeaderConsts.CLIENT_VERSION_HEADER, VersionUtils.version); + header.addParam(HttpHeaderConsts.USER_AGENT_HEADER, UtilAndComs.VERSION); + header.addParam(HttpHeaderConsts.ACCEPT_ENCODING, "gzip,deflate,sdch"); + header.addParam(HttpHeaderConsts.CONNECTION, "Keep-Alive"); + header.addParam(HttpHeaderConsts.REQUEST_ID, UuidUtils.generateUuid()); + header.addParam(HttpHeaderConsts.REQUEST_MODULE, "Naming"); + return header; } private static String getSignData(String serviceName) { diff --git a/client/src/main/java/com/alibaba/nacos/client/security/SecurityProxy.java b/client/src/main/java/com/alibaba/nacos/client/security/SecurityProxy.java index 852ea143e95..4b37eb07b5b 100644 --- a/client/src/main/java/com/alibaba/nacos/client/security/SecurityProxy.java +++ b/client/src/main/java/com/alibaba/nacos/client/security/SecurityProxy.java @@ -17,18 +17,21 @@ import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.common.Constants; -import com.alibaba.nacos.client.naming.net.HttpClient; -import com.alibaba.nacos.common.utils.HttpMethod; +import com.alibaba.nacos.client.naming.net.NamingHttpClientManager; +import com.alibaba.nacos.common.http.HttpRestResult; +import com.alibaba.nacos.common.http.client.NacosRestTemplate; +import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.StringUtils; import com.fasterxml.jackson.databind.JsonNode; -import org.apache.commons.codec.Charsets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.net.HttpURLConnection; -import java.util.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; import java.util.concurrent.TimeUnit; /** @@ -43,6 +46,8 @@ public class SecurityProxy { private static final String LOGIN_URL = "/v1/auth/users/login"; + private NacosRestTemplate nacosRestTemplate = NamingHttpClientManager.getNacosRestTemplate(); + private String contextPath; /** @@ -110,28 +115,31 @@ public boolean login(String server) { if (StringUtils.isNotBlank(username)) { Map params = new HashMap(2); + Map bodyMap = new HashMap<>(2); params.put("username", username); - String body = "password=" + password; + bodyMap.put("password", password); String url = "http://" + server + contextPath + LOGIN_URL; if (server.contains(Constants.HTTP_PREFIX)) { url = server + contextPath + LOGIN_URL; } - - HttpClient.HttpResult result = HttpClient.request(url, new ArrayList(2), - params, body, Charsets.UTF_8.name(), HttpMethod.POST); - - if (result.code != HttpURLConnection.HTTP_OK) { - SECURITY_LOGGER.error("login failed: {}", JacksonUtils.toJson(result)); + try { + HttpRestResult restResult = nacosRestTemplate.postForm(url, Header.EMPTY, params, bodyMap, String.class); + if (!restResult.ok()) { + SECURITY_LOGGER.error("login failed: {}", JacksonUtils.toJson(restResult)); + return false; + } + JsonNode obj = JacksonUtils.toObj(restResult.getData()); + if (obj.has(Constants.ACCESS_TOKEN)) { + accessToken = obj.get(Constants.ACCESS_TOKEN).asText(); + tokenTtl = obj.get(Constants.TOKEN_TTL).asInt(); + tokenRefreshWindow = tokenTtl / 10; + } + } catch (Exception e) { + SECURITY_LOGGER.error("[SecurityProxy] login http request failed" + + " url: {}, params: {}, bodyMap: {}, errorMsg: {}", url, params, bodyMap, e.getMessage()); return false; } - - JsonNode obj = JacksonUtils.toObj(result.content); - if (obj.has(Constants.ACCESS_TOKEN)) { - accessToken = obj.get(Constants.ACCESS_TOKEN).asText(); - tokenTtl = obj.get(Constants.TOKEN_TTL).asInt(); - tokenRefreshWindow = tokenTtl / 10; - } } return true; } diff --git a/common/src/main/java/com/alibaba/nacos/common/http/BaseHttpMethod.java b/common/src/main/java/com/alibaba/nacos/common/http/BaseHttpMethod.java index 5b0f6624800..5caea1577c3 100644 --- a/common/src/main/java/com/alibaba/nacos/common/http/BaseHttpMethod.java +++ b/common/src/main/java/com/alibaba/nacos/common/http/BaseHttpMethod.java @@ -193,7 +193,7 @@ public void initEntity(Object body, String mediaType) throws Exception { * @throws Exception exception */ public void initFromEntity(Map body, String charset) throws Exception { - if (body.isEmpty()) { + if (body == null || body.isEmpty()) { return; } List params = new ArrayList(body.size()); diff --git a/common/src/main/java/com/alibaba/nacos/common/http/HttpClientBeanHolder.java b/common/src/main/java/com/alibaba/nacos/common/http/HttpClientBeanHolder.java index f5c5729815a..18d28a72528 100644 --- a/common/src/main/java/com/alibaba/nacos/common/http/HttpClientBeanHolder.java +++ b/common/src/main/java/com/alibaba/nacos/common/http/HttpClientBeanHolder.java @@ -37,15 +37,9 @@ public final class HttpClientBeanHolder { private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientManager.class); - private static final int TIMEOUT = Integer.getInteger("nacos.http.timeout", 5000); - - private static final HttpClientConfig HTTP_CLIENT_CONFIG = HttpClientConfig.builder().setConTimeOutMillis(TIMEOUT) - .setReadTimeOutMillis(TIMEOUT >> 1).build(); - private static final Map SINGLETON_REST = new HashMap(10); - private static final Map SINGLETON_ASYNC_REST = new HashMap( - 10); + private static final Map SINGLETON_ASYNC_REST = new HashMap(10); private static final AtomicBoolean ALREADY_SHUTDOWN = new AtomicBoolean(false); diff --git a/common/src/main/java/com/alibaba/nacos/common/http/client/HttpClientResponse.java b/common/src/main/java/com/alibaba/nacos/common/http/client/HttpClientResponse.java index 0b9e2ab325f..0aaac2f3833 100644 --- a/common/src/main/java/com/alibaba/nacos/common/http/client/HttpClientResponse.java +++ b/common/src/main/java/com/alibaba/nacos/common/http/client/HttpClientResponse.java @@ -26,7 +26,6 @@ * Represents a client-side HTTP response. * * @author mai.jh - * @date 2020/5/23 */ public interface HttpClientResponse extends Closeable { diff --git a/common/src/main/java/com/alibaba/nacos/common/http/client/NacosAsyncRestTemplate.java b/common/src/main/java/com/alibaba/nacos/common/http/client/NacosAsyncRestTemplate.java index 1470fd46f80..38566fac08f 100644 --- a/common/src/main/java/com/alibaba/nacos/common/http/client/NacosAsyncRestTemplate.java +++ b/common/src/main/java/com/alibaba/nacos/common/http/client/NacosAsyncRestTemplate.java @@ -197,7 +197,7 @@ public void putJson(String url, Header header, Map paramValu * @param callback callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} * @throws Exception ex */ - public void putFrom(String url, Header header, Query query, Map bodyValues, Type responseType, + public void putForm(String url, Header header, Query query, Map bodyValues, Type responseType, Callback callback) throws Exception { execute(url, HttpMethod.PUT, new RequestHttpEntity(header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), query, bodyValues), @@ -223,7 +223,7 @@ public void putFrom(String url, Header header, Query query, Map void putFrom(String url, Header header, Map paramValues, Map bodyValues, + public void putForm(String url, Header header, Map paramValues, Map bodyValues, Type responseType, Callback callback) throws Exception { execute(url, HttpMethod.PUT, new RequestHttpEntity(header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), Query.newInstance().initParams(paramValues), bodyValues), responseType, callback); @@ -296,7 +296,7 @@ public void postJson(String url, Header header, Map paramVal * @param callback callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} * @throws Exception ex */ - public void postFrom(String url, Header header, Query query, Map bodyValues, Type responseType, + public void postForm(String url, Header header, Query query, Map bodyValues, Type responseType, Callback callback) throws Exception { execute(url, HttpMethod.POST, new RequestHttpEntity(header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), query, bodyValues), @@ -322,7 +322,7 @@ public void postFrom(String url, Header header, Query query, Map void postFrom(String url, Header header, Map paramValues, Map bodyValues, + public void postForm(String url, Header header, Map paramValues, Map bodyValues, Type responseType, Callback callback) throws Exception { execute(url, HttpMethod.POST, new RequestHttpEntity(header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), diff --git a/common/src/main/java/com/alibaba/nacos/common/http/client/NacosRestTemplate.java b/common/src/main/java/com/alibaba/nacos/common/http/client/NacosRestTemplate.java index b22a7035b4f..cda70b5dec4 100644 --- a/common/src/main/java/com/alibaba/nacos/common/http/client/NacosRestTemplate.java +++ b/common/src/main/java/com/alibaba/nacos/common/http/client/NacosRestTemplate.java @@ -35,7 +35,6 @@ * Nacos rest template Interface specifying a basic set of RESTful operations. * * @author mai.jh - * @date 2020/5/24 * @see HttpClientRequest * @see HttpClientResponse */ @@ -178,7 +177,7 @@ public HttpRestResult putJson(String url, Header header, Map HttpRestResult putFrom(String url, Header header, Query query, Map bodyValues, + public HttpRestResult putForm(String url, Header header, Query query, Map bodyValues, Type responseType) throws Exception { RequestHttpEntity requestHttpEntity = new RequestHttpEntity( header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), query, bodyValues); @@ -201,7 +200,7 @@ public HttpRestResult putFrom(String url, Header header, Query query, Map * @return {@link HttpRestResult} * @throws Exception ex */ - public HttpRestResult putFrom(String url, Header header, Map paramValues, + public HttpRestResult putForm(String url, Header header, Map paramValues, Map bodyValues, Type responseType) throws Exception { RequestHttpEntity requestHttpEntity = new RequestHttpEntity( header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), @@ -268,7 +267,7 @@ public HttpRestResult postJson(String url, Header header, Map HttpRestResult postFrom(String url, Header header, Query query, Map bodyValues, + public HttpRestResult postForm(String url, Header header, Query query, Map bodyValues, Type responseType) throws Exception { RequestHttpEntity requestHttpEntity = new RequestHttpEntity( header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), query, bodyValues); @@ -291,7 +290,7 @@ public HttpRestResult postFrom(String url, Header header, Query query, Ma * @return {@link HttpRestResult} * @throws Exception ex */ - public HttpRestResult postFrom(String url, Header header, Map paramValues, + public HttpRestResult postForm(String url, Header header, Map paramValues, Map bodyValues, Type responseType) throws Exception { RequestHttpEntity requestHttpEntity = new RequestHttpEntity( header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), @@ -299,6 +298,28 @@ public HttpRestResult postFrom(String url, Header header, Map HttpRestResult exchangeForm(String url, Header header, + Map paramValues, Map bodyValues, String httpMethod, Type responseType) throws Exception{ + RequestHttpEntity requestHttpEntity = new RequestHttpEntity( + header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), + Query.newInstance().initParams(paramValues), + bodyValues); + return execute(url, httpMethod, requestHttpEntity, responseType); + } + private HttpRestResult execute(String url, String httpMethod, RequestHttpEntity requestEntity, Type responseType) throws Exception { URI uri = HttpUtils.buildUri(url, requestEntity.getQuery()); diff --git a/common/src/main/java/com/alibaba/nacos/common/http/handler/ResponseHandler.java b/common/src/main/java/com/alibaba/nacos/common/http/handler/ResponseHandler.java index 071cc319799..2237324a198 100644 --- a/common/src/main/java/com/alibaba/nacos/common/http/handler/ResponseHandler.java +++ b/common/src/main/java/com/alibaba/nacos/common/http/handler/ResponseHandler.java @@ -78,14 +78,22 @@ public static HttpRestResult responseEntityExtractor(HttpClientResponse r String contentType = headers.getValue(HttpHeaderConsts.CONTENT_TYPE); InputStream body = response.getBody(); T extractBody = null; + final boolean typeToStr = String.class.toString().equals(type.toString()); if (contentType != null && contentType.startsWith(MediaType.APPLICATION_JSON) && HttpStatus.SC_OK == response - .getStatusCode()) { - extractBody = convert(body, type); + .getStatusCode()) { + // When the type is string type and the response contentType is [application/json], + // then it should be serialized as string + if (typeToStr) { + extractBody = (T) IoUtils.toString(body, headers.getCharset()); + } else { + extractBody = convert(body, type); + } } if (extractBody == null) { - if (!String.class.toString().equals(type.toString())) { + if (!typeToStr) { LOGGER.error( - "if the response contentType is not [application/json]," + " only support to java.lang.String"); + "if the response contentType is not [application/json]," + + " only support to java.lang.String"); throw new NacosDeserializationException(type); } extractBody = (T) IoUtils.toString(body, headers.getCharset()); diff --git a/test/src/test/java/com/alibaba/nacos/test/common/NacosAsyncRestTemplate_ITCase.java b/test/src/test/java/com/alibaba/nacos/test/common/NacosAsyncRestTemplate_ITCase.java index 951e7531f5b..307927e6d5a 100644 --- a/test/src/test/java/com/alibaba/nacos/test/common/NacosAsyncRestTemplate_ITCase.java +++ b/test/src/test/java/com/alibaba/nacos/test/common/NacosAsyncRestTemplate_ITCase.java @@ -88,14 +88,14 @@ public Throwable getThrowable() { } @Test - public void test_url_post_from() throws Exception{ + public void test_url_post_form() throws Exception{ String url = IP + CONFIG_INSTANCE_PATH + "/instance"; Map param = new HashMap<>(); param.put("serviceName", "app-test"); param.put("port", "8080"); param.put("ip", "11.11.11.11"); CallbackMap callbackMap = new CallbackMap<>(); - nacosRestTemplate.postFrom(url, Header.newInstance(), Query.newInstance(), param, String.class, callbackMap); + nacosRestTemplate.postForm(url, Header.newInstance(), Query.newInstance(), param, String.class, callbackMap); Thread.sleep(2000); HttpRestResult restResult = callbackMap.getRestResult(); System.out.println(restResult.getData()); @@ -104,14 +104,14 @@ public void test_url_post_from() throws Exception{ } @Test - public void test_url_put_from() throws Exception{ + public void test_url_put_form() throws Exception{ String url = IP + CONFIG_INSTANCE_PATH + "/instance"; Map param = new HashMap<>(); param.put("serviceName", "app-test-change"); param.put("port", "8080"); param.put("ip", "11.11.11.11"); CallbackMap callbackMap = new CallbackMap<>(); - nacosRestTemplate.putFrom(url, Header.newInstance(), Query.newInstance(), param, String.class, callbackMap); + nacosRestTemplate.postForm(url, Header.newInstance(), Query.newInstance(), param, String.class, callbackMap); Thread.sleep(2000); HttpRestResult restResult = callbackMap.getRestResult(); System.out.println(restResult.getData()); diff --git a/test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_ITCase.java b/test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_ITCase.java index d33fe1f61cb..296220f3b3f 100644 --- a/test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_ITCase.java +++ b/test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_ITCase.java @@ -69,7 +69,7 @@ public void test_url_post_config() throws Exception { param.put("dataId", "test-1"); param.put("group", "DEFAULT_GROUP"); param.put("content", "aaa=b"); - HttpRestResult restResult = nacosRestTemplate.postFrom(url, Header.newInstance(), Query.EMPTY, param, String.class); + HttpRestResult restResult = nacosRestTemplate.postForm(url, Header.newInstance(), Query.EMPTY, param, String.class); Assert.assertTrue(restResult.ok()); System.out.println(restResult.getData()); System.out.println(restResult.getHeader()); @@ -87,13 +87,13 @@ public void test_url_get_return_restResult() throws Exception{ @Test - public void test_url_post_from() throws Exception{ + public void test_url_post_form() throws Exception{ String url = IP + INSTANCE_PATH + "/instance"; Map param = new HashMap<>(); param.put("serviceName", "app-test"); param.put("port", "8080"); param.put("ip", "11.11.11.11"); - HttpRestResult restResult = nacosRestTemplate.postFrom(url, Header.newInstance(), Query.newInstance(), param, String.class); + HttpRestResult restResult = nacosRestTemplate.postForm(url, Header.newInstance(), Query.newInstance(), param, String.class); Assert.assertTrue(restResult.ok()); System.out.println(restResult.getData()); } @@ -105,7 +105,7 @@ public void test_url_put_from() throws Exception{ param.put("serviceName", "app-test-change"); param.put("port", "8080"); param.put("ip", "11.11.11.11"); - HttpRestResult restResult = nacosRestTemplate.putFrom(url, Header.newInstance(), Query.newInstance(), param, String.class); + HttpRestResult restResult = nacosRestTemplate.putForm(url, Header.newInstance(), Query.newInstance(), param, String.class); Assert.assertTrue(restResult.ok()); System.out.println(restResult.getData()); } diff --git a/test/src/test/java/com/alibaba/nacos/test/naming/AutoDeregisterInstance_ITCase.java b/test/src/test/java/com/alibaba/nacos/test/naming/AutoDeregisterInstance_ITCase.java index 5d7c98203ad..68982265149 100644 --- a/test/src/test/java/com/alibaba/nacos/test/naming/AutoDeregisterInstance_ITCase.java +++ b/test/src/test/java/com/alibaba/nacos/test/naming/AutoDeregisterInstance_ITCase.java @@ -74,7 +74,7 @@ public void init() throws Exception { } @After - public void destroy() { + public void destroy() throws Exception{ NamingBase.destoryServer(port); } diff --git a/test/src/test/java/com/alibaba/nacos/test/naming/NamingBase.java b/test/src/test/java/com/alibaba/nacos/test/naming/NamingBase.java index e995e9c3c64..c06ccb8aafd 100644 --- a/test/src/test/java/com/alibaba/nacos/test/naming/NamingBase.java +++ b/test/src/test/java/com/alibaba/nacos/test/naming/NamingBase.java @@ -16,10 +16,13 @@ package com.alibaba.nacos.test.naming; import com.alibaba.nacos.api.naming.pojo.Instance; -import com.alibaba.nacos.client.naming.net.HttpClient; +import com.alibaba.nacos.client.naming.net.NamingHttpClientManager; import com.alibaba.nacos.common.constant.HttpHeaderConsts; +import com.alibaba.nacos.common.http.HttpRestResult; +import com.alibaba.nacos.common.http.client.NacosRestTemplate; +import com.alibaba.nacos.common.http.param.Header; +import com.alibaba.nacos.common.http.param.Query; import com.alibaba.nacos.test.base.HttpClient4Test; -import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; import org.junit.Assert; @@ -30,6 +33,7 @@ */ public class NamingBase extends HttpClient4Test { + private static final NacosRestTemplate nacosRestTemplate = NamingHttpClientManager.getNacosRestTemplate(); public static final String TEST_DOM_1 = "nacos.test.1"; public static final String TEST_IP_4_DOM_1 = "127.0.0.1"; @@ -166,39 +170,32 @@ public static boolean verifyInstanceList(List instanceList1, List headers = new ArrayList(); - headers.add(HttpHeaderConsts.USER_AGENT_HEADER); - headers.add("Nacos-Server"); - HttpClient.HttpResult result = - HttpClient.request(url, headers, new HashMap(), StringUtils.EMPTY, "UTF-8", "PUT"); + Header header = Header.newInstance(); + header.addParam(HttpHeaderConsts.USER_AGENT_HEADER, "Nacos-Server"); + HttpRestResult result = nacosRestTemplate.putForm(url, header, Query.EMPTY, new HashMap<>(), String.class); System.out.println(result); - Assert.assertEquals(HttpStatus.SC_OK, result.code); - + Assert.assertEquals(HttpStatus.SC_OK, result.getCode()); url = "http://127.0.0.1:" + localPort + "/nacos/v1/ns/operator/switches?entry=autoChangeHealthCheckEnabled&value=" + false; - headers = new ArrayList(); - headers.add(HttpHeaderConsts.USER_AGENT_HEADER); - headers.add("Nacos-Server"); - result = - HttpClient.request(url, headers, new HashMap(), StringUtils.EMPTY, "UTF-8", "PUT"); + + result = nacosRestTemplate.putForm(url, header, Query.EMPTY, new HashMap<>(), String.class); System.out.println(result); - Assert.assertEquals(HttpStatus.SC_OK, result.code); + Assert.assertEquals(HttpStatus.SC_OK, result.getCode()); } - public static void destoryServer(int localPort) { + public static void destoryServer(int localPort) throws Exception{ String url = "http://127.0.0.1:" + localPort + "/nacos/v1/ns/operator/switches?entry=autoChangeHealthCheckEnabled&value=" + true; - List headers = new ArrayList(); - headers.add(HttpHeaderConsts.USER_AGENT_HEADER); - headers.add("Nacos-Server"); - HttpClient.HttpResult result = - HttpClient.request(url, headers, new HashMap(), StringUtils.EMPTY, "UTF-8", "PUT"); + Header header = Header.newInstance(); + header.addParam(HttpHeaderConsts.USER_AGENT_HEADER, "Nacos-Server"); + + HttpRestResult result = nacosRestTemplate.putForm(url, header, Query.EMPTY, new HashMap<>(), String.class); System.out.println(result); - Assert.assertEquals(HttpStatus.SC_OK, result.code); + Assert.assertEquals(HttpStatus.SC_OK, result.getCode()); } }