[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
This commit is contained in:
mai.jh 2020-06-22 20:42:46 +08:00 committed by GitHub
parent 1dc29f2d52
commit 6ce8d8ca79
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 161 additions and 119 deletions

View File

@ -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 @@ import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
/**
* @author nkorange
* @deprecated Use NacosRestTemplate{@link NacosRestTemplate} unified http client
*/
@Deprecated
public class HttpClient {
public static final int READ_TIME_OUT_MILLIS = Integer

View File

@ -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()

View File

@ -37,15 +37,19 @@ import com.alibaba.nacos.client.security.SecurityProxy;
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.List;
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 @@ import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
*/
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 class NamingProxy implements Closeable {
try {
String urlString = "http://" + endpoint + "/nacos/serverlist";
List<String> headers = builderHeaders();
HttpClient.HttpResult result = HttpClient.httpGet(urlString, headers, null, UtilAndComs.ENCODING);
if (HttpURLConnection.HTTP_OK != result.code) {
Header header = builderHeader();
HttpRestResult<String> 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<String> list = new ArrayList<String>();
for (String line : IoUtils.readLines(new StringReader(content))) {
if (!line.trim().isEmpty()) {
@ -333,10 +339,10 @@ public class NamingProxy implements Closeable {
NAMING_LOGGER.debug("[BEAT] {} sending beat to server: {}", namespaceId, beatInfo.toString());
}
Map<String, String> params = new HashMap<String, String>(8);
String body = StringUtils.EMPTY;
Map<String, String> bodyMap = new HashMap<String, String>(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 class NamingProxy implements Closeable {
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 class NamingProxy implements Closeable {
}
public String reqAPI(String api, Map<String, String> 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<String, String> params, String body, String method) throws NacosException {
public String reqAPI(String api, Map<String, String> params, Map<String, String> body, String method) throws NacosException {
return reqAPI(api, params, body, getServerList(), method);
}
@ -414,16 +420,16 @@ public class NamingProxy implements Closeable {
return snapshot;
}
public String callServer(String api, Map<String, String> params, String body, String curServer) throws NacosException {
public String callServer(String api, Map<String, String> params, Map<String, String> body, String curServer) throws NacosException {
return callServer(api, params, body, curServer, HttpMethod.GET);
}
public String callServer(String api, Map<String, String> params, String body, String curServer, String method)
public String callServer(String api, Map<String, String> params, Map<String, String> body, String curServer, String method)
throws NacosException {
long start = System.currentTimeMillis();
long end = 0;
injectSecurityInfo(params);
List<String> headers = builderHeaders();
Header header = builderHeader();
String url;
if (curServer.startsWith(UtilAndComs.HTTPS) || curServer.startsWith(UtilAndComs.HTTP)) {
@ -432,27 +438,30 @@ public class NamingProxy implements Closeable {
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();
try {
HttpRestResult<String> restResult = nacosRestTemplate.exchangeForm(url, header, params, body, method, String.class);
end = System.currentTimeMillis();
MetricsMonitor.getNamingRequestMonitor(method, url, String.valueOf(result.code))
.observe(end - start);
MetricsMonitor.getNamingRequestMonitor(method, url, String.valueOf(restResult.getCode()))
.observe(end - start);
if (HttpURLConnection.HTTP_OK == result.code) {
return result.content;
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);
}
if (HttpURLConnection.HTTP_NOT_MODIFIED == result.code) {
return StringUtils.EMPTY;
}
throw new NacosException(result.code, result.content);
}
public String reqAPI(String api, Map<String, String> params, String body, List<String> servers, String method) throws NacosException {
public String reqAPI(String api, Map<String, String> params, Map<String, String> body, List<String> servers, String method) throws NacosException {
params.put(CommonParams.NAMESPACE_ID, getNamespaceId());
@ -526,14 +535,15 @@ public class NamingProxy implements Closeable {
}
}
public List<String> builderHeaders() {
List<String> 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) {

View File

@ -17,18 +17,21 @@ package com.alibaba.nacos.client.security;
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 class SecurityProxy {
if (StringUtils.isNotBlank(username)) {
Map<String, String> params = new HashMap<String, String>(2);
Map<String, String> 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<String>(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<String> 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;
}

View File

@ -193,7 +193,7 @@ public enum BaseHttpMethod {
* @throws Exception exception
*/
public void initFromEntity(Map<String, String> body, String charset) throws Exception {
if (body.isEmpty()) {
if (body == null || body.isEmpty()) {
return;
}
List<NameValuePair> params = new ArrayList<NameValuePair>(body.size());

View File

@ -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<String, NacosRestTemplate> SINGLETON_REST = new HashMap<String, NacosRestTemplate>(10);
private static final Map<String, NacosAsyncRestTemplate> SINGLETON_ASYNC_REST = new HashMap<String, NacosAsyncRestTemplate>(
10);
private static final Map<String, NacosAsyncRestTemplate> SINGLETON_ASYNC_REST = new HashMap<String, NacosAsyncRestTemplate>(10);
private static final AtomicBoolean ALREADY_SHUTDOWN = new AtomicBoolean(false);

View File

@ -26,7 +26,6 @@ import java.io.InputStream;
* Represents a client-side HTTP response.
*
* @author mai.jh
* @date 2020/5/23
*/
public interface HttpClientResponse extends Closeable {

View File

@ -197,7 +197,7 @@ public class NacosAsyncRestTemplate {
* @param callback callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)}
* @throws Exception ex
*/
public <T> void putFrom(String url, Header header, Query query, Map<String, String> bodyValues, Type responseType,
public <T> void putForm(String url, Header header, Query query, Map<String, String> bodyValues, Type responseType,
Callback<T> callback) throws Exception {
execute(url, HttpMethod.PUT,
new RequestHttpEntity(header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), query, bodyValues),
@ -223,7 +223,7 @@ public class NacosAsyncRestTemplate {
* @param callback callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)}
* @throws Exception ex
*/
public <T> void putFrom(String url, Header header, Map<String, String> paramValues, Map<String, String> bodyValues,
public <T> void putForm(String url, Header header, Map<String, String> paramValues, Map<String, String> bodyValues,
Type responseType, Callback<T> 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 class NacosAsyncRestTemplate {
* @param callback callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)}
* @throws Exception ex
*/
public <T> void postFrom(String url, Header header, Query query, Map<String, String> bodyValues, Type responseType,
public <T> void postForm(String url, Header header, Query query, Map<String, String> bodyValues, Type responseType,
Callback<T> callback) throws Exception {
execute(url, HttpMethod.POST,
new RequestHttpEntity(header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), query, bodyValues),
@ -322,7 +322,7 @@ public class NacosAsyncRestTemplate {
* @param callback callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)}
* @throws Exception ex
*/
public <T> void postFrom(String url, Header header, Map<String, String> paramValues, Map<String, String> bodyValues,
public <T> void postForm(String url, Header header, Map<String, String> paramValues, Map<String, String> bodyValues,
Type responseType, Callback<T> callback) throws Exception {
execute(url, HttpMethod.POST,
new RequestHttpEntity(header.setContentType(MediaType.APPLICATION_FORM_URLENCODED),

View File

@ -35,7 +35,6 @@ import java.util.Map;
* 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 class NacosRestTemplate {
* @return {@link HttpRestResult}
* @throws Exception ex
*/
public <T> HttpRestResult<T> putFrom(String url, Header header, Query query, Map<String, String> bodyValues,
public <T> HttpRestResult<T> putForm(String url, Header header, Query query, Map<String, String> bodyValues,
Type responseType) throws Exception {
RequestHttpEntity requestHttpEntity = new RequestHttpEntity(
header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), query, bodyValues);
@ -201,7 +200,7 @@ public class NacosRestTemplate {
* @return {@link HttpRestResult}
* @throws Exception ex
*/
public <T> HttpRestResult<T> putFrom(String url, Header header, Map<String, String> paramValues,
public <T> HttpRestResult<T> putForm(String url, Header header, Map<String, String> paramValues,
Map<String, String> bodyValues, Type responseType) throws Exception {
RequestHttpEntity requestHttpEntity = new RequestHttpEntity(
header.setContentType(MediaType.APPLICATION_FORM_URLENCODED),
@ -268,7 +267,7 @@ public class NacosRestTemplate {
* @return {@link HttpRestResult}
* @throws Exception ex
*/
public <T> HttpRestResult<T> postFrom(String url, Header header, Query query, Map<String, String> bodyValues,
public <T> HttpRestResult<T> postForm(String url, Header header, Query query, Map<String, String> bodyValues,
Type responseType) throws Exception {
RequestHttpEntity requestHttpEntity = new RequestHttpEntity(
header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), query, bodyValues);
@ -291,7 +290,7 @@ public class NacosRestTemplate {
* @return {@link HttpRestResult}
* @throws Exception ex
*/
public <T> HttpRestResult<T> postFrom(String url, Header header, Map<String, String> paramValues,
public <T> HttpRestResult<T> postForm(String url, Header header, Map<String, String> paramValues,
Map<String, String> bodyValues, Type responseType) throws Exception {
RequestHttpEntity requestHttpEntity = new RequestHttpEntity(
header.setContentType(MediaType.APPLICATION_FORM_URLENCODED),
@ -299,6 +298,28 @@ public class NacosRestTemplate {
return execute(url, HttpMethod.POST, requestHttpEntity, responseType);
}
/**
* Execute the HTTP method to the given URI template, writing the given request entity to the request, and
* returns the response as {@link HttpRestResult}.
*
* @param url url
* @param header http header param
* @param paramValues http query param
* @param bodyValues http body param
* @param httpMethod http method
* @param responseType return type
* @return {@link HttpRestResult}
* @throws Exception ex
*/
public <T> HttpRestResult<T> exchangeForm(String url, Header header,
Map<String, String> paramValues, Map<String, String> 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 <T> HttpRestResult<T> execute(String url, String httpMethod, RequestHttpEntity requestEntity,
Type responseType) throws Exception {
URI uri = HttpUtils.buildUri(url, requestEntity.getQuery());

View File

@ -78,14 +78,22 @@ public final class ResponseHandler {
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());

View File

@ -88,14 +88,14 @@ public class NacosAsyncRestTemplate_ITCase {
}
@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<String, String> param = new HashMap<>();
param.put("serviceName", "app-test");
param.put("port", "8080");
param.put("ip", "11.11.11.11");
CallbackMap<String> 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<String> restResult = callbackMap.getRestResult();
System.out.println(restResult.getData());
@ -104,14 +104,14 @@ public class NacosAsyncRestTemplate_ITCase {
}
@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<String, String> param = new HashMap<>();
param.put("serviceName", "app-test-change");
param.put("port", "8080");
param.put("ip", "11.11.11.11");
CallbackMap<String> 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<String> restResult = callbackMap.getRestResult();
System.out.println(restResult.getData());

View File

@ -69,7 +69,7 @@ public class NacosRestTemplate_ITCase {
param.put("dataId", "test-1");
param.put("group", "DEFAULT_GROUP");
param.put("content", "aaa=b");
HttpRestResult<String> restResult = nacosRestTemplate.postFrom(url, Header.newInstance(), Query.EMPTY, param, String.class);
HttpRestResult<String> 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 class NacosRestTemplate_ITCase {
@Test
public void test_url_post_from() throws Exception{
public void test_url_post_form() throws Exception{
String url = IP + INSTANCE_PATH + "/instance";
Map<String, String> param = new HashMap<>();
param.put("serviceName", "app-test");
param.put("port", "8080");
param.put("ip", "11.11.11.11");
HttpRestResult<String> restResult = nacosRestTemplate.postFrom(url, Header.newInstance(), Query.newInstance(), param, String.class);
HttpRestResult<String> 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 class NacosRestTemplate_ITCase {
param.put("serviceName", "app-test-change");
param.put("port", "8080");
param.put("ip", "11.11.11.11");
HttpRestResult<String> restResult = nacosRestTemplate.putFrom(url, Header.newInstance(), Query.newInstance(), param, String.class);
HttpRestResult<String> restResult = nacosRestTemplate.putForm(url, Header.newInstance(), Query.newInstance(), param, String.class);
Assert.assertTrue(restResult.ok());
System.out.println(restResult.getData());
}

View File

@ -74,7 +74,7 @@ public class AutoDeregisterInstance_ITCase {
}
@After
public void destroy() {
public void destroy() throws Exception{
NamingBase.destoryServer(port);
}

View File

@ -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 @@ import java.util.*;
*/
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 class NamingBase extends HttpClient4Test {
return true;
}
public static void prepareServer(int localPort) {
public static void prepareServer(int localPort) throws Exception{
prepareServer(localPort, "UP");
}
public static void prepareServer(int localPort, String status) {
public static void prepareServer(int localPort, String status) throws Exception {
String url = "http://127.0.0.1:" + localPort + "/nacos/v1/ns/operator/switches?entry=overriddenServerStatus&value=" + status;
List<String> headers = new ArrayList<String>();
headers.add(HttpHeaderConsts.USER_AGENT_HEADER);
headers.add("Nacos-Server");
HttpClient.HttpResult result =
HttpClient.request(url, headers, new HashMap<String, String>(), StringUtils.EMPTY, "UTF-8", "PUT");
Header header = Header.newInstance();
header.addParam(HttpHeaderConsts.USER_AGENT_HEADER, "Nacos-Server");
HttpRestResult<String> 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<String>();
headers.add(HttpHeaderConsts.USER_AGENT_HEADER);
headers.add("Nacos-Server");
result =
HttpClient.request(url, headers, new HashMap<String, String>(), 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<String> headers = new ArrayList<String>();
headers.add(HttpHeaderConsts.USER_AGENT_HEADER);
headers.add("Nacos-Server");
HttpClient.HttpResult result =
HttpClient.request(url, headers, new HashMap<String, String>(), StringUtils.EMPTY, "UTF-8", "PUT");
Header header = Header.newInstance();
header.addParam(HttpHeaderConsts.USER_AGENT_HEADER, "Nacos-Server");
HttpRestResult<String> 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());
}
}