Search in sources :

Example 1 with Header

use of com.alibaba.nacos.common.http.param.Header in project nacos by alibaba.

the class DefaultHttpClientRequest method build.

static HttpRequestBase build(URI uri, String method, RequestHttpEntity requestHttpEntity) throws Exception {
    final Header headers = requestHttpEntity.getHeaders();
    final BaseHttpMethod httpMethod = BaseHttpMethod.sourceOf(method);
    final HttpRequestBase httpRequestBase = httpMethod.init(uri.toString());
    HttpUtils.initRequestHeader(httpRequestBase, headers);
    if (MediaType.APPLICATION_FORM_URLENCODED.equals(headers.getValue(HttpHeaderConsts.CONTENT_TYPE)) && requestHttpEntity.getBody() instanceof Map) {
        HttpUtils.initRequestFromEntity(httpRequestBase, (Map<String, String>) requestHttpEntity.getBody(), headers.getCharset());
    } else {
        HttpUtils.initRequestEntity(httpRequestBase, requestHttpEntity.getBody(), headers);
    }
    replaceDefaultConfig(httpRequestBase, requestHttpEntity.getHttpClientConfig());
    return httpRequestBase;
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) Header(com.alibaba.nacos.common.http.param.Header) BaseHttpMethod(com.alibaba.nacos.common.http.BaseHttpMethod) Map(java.util.Map)

Example 2 with Header

use of com.alibaba.nacos.common.http.param.Header in project nacos by alibaba.

the class ServerHttpAgent method httpDelete.

@Override
public HttpRestResult<String> httpDelete(String path, Map<String, String> headers, Map<String, String> paramValues, String encode, long readTimeoutMs) throws Exception {
    final long endTime = System.currentTimeMillis() + readTimeoutMs;
    String currentServerAddr = serverListMgr.getCurrentServerAddr();
    int maxRetry = this.maxRetry;
    HttpClientConfig httpConfig = HttpClientConfig.builder().setReadTimeOutMillis(Long.valueOf(readTimeoutMs).intValue()).setConTimeOutMillis(ConfigHttpClientManager.getInstance().getConnectTimeoutOrDefault(100)).build();
    do {
        try {
            Header newHeaders = Header.newInstance();
            if (headers != null) {
                newHeaders.addAll(headers);
            }
            Query query = Query.newInstance().initParams(paramValues);
            HttpRestResult<String> result = NACOS_RESTTEMPLATE.delete(getUrl(currentServerAddr, path), httpConfig, newHeaders, query, String.class);
            if (isFail(result)) {
                LOGGER.error("[NACOS ConnectException] currentServerAddr: {}, httpCode: {}", serverListMgr.getCurrentServerAddr(), result.getCode());
            } else {
                // Update the currently available server addr
                serverListMgr.updateCurrentServerAddr(currentServerAddr);
                return result;
            }
        } catch (ConnectException connectException) {
            LOGGER.error("[NACOS ConnectException httpDelete] currentServerAddr:{}, err : {}", serverListMgr.getCurrentServerAddr(), ExceptionUtil.getStackTrace(connectException));
        } catch (SocketTimeoutException stoe) {
            LOGGER.error("[NACOS SocketTimeoutException httpDelete] currentServerAddr:{}, err : {}", serverListMgr.getCurrentServerAddr(), ExceptionUtil.getStackTrace(stoe));
        } catch (Exception ex) {
            LOGGER.error("[NACOS Exception httpDelete] currentServerAddr: " + serverListMgr.getCurrentServerAddr(), ex);
            throw ex;
        }
        if (serverListMgr.getIterator().hasNext()) {
            currentServerAddr = serverListMgr.getIterator().next();
        } else {
            maxRetry--;
            if (maxRetry < 0) {
                throw new ConnectException("[NACOS HTTP-DELETE] The maximum number of tolerable server reconnection errors has been reached");
            }
            serverListMgr.refreshCurrentServerAddr();
        }
    } while (System.currentTimeMillis() <= endTime);
    LOGGER.error("no available server");
    throw new ConnectException("no available server");
}
Also used : HttpClientConfig(com.alibaba.nacos.common.http.HttpClientConfig) SocketTimeoutException(java.net.SocketTimeoutException) Header(com.alibaba.nacos.common.http.param.Header) Query(com.alibaba.nacos.common.http.param.Query) SocketTimeoutException(java.net.SocketTimeoutException) NacosException(com.alibaba.nacos.api.exception.NacosException) ConnectException(java.net.ConnectException) ConnectException(java.net.ConnectException)

Example 3 with Header

use of com.alibaba.nacos.common.http.param.Header in project nacos by alibaba.

the class ServerHttpAgent method httpGet.

@Override
public HttpRestResult<String> httpGet(String path, Map<String, String> headers, Map<String, String> paramValues, String encode, long readTimeoutMs) throws Exception {
    final long endTime = System.currentTimeMillis() + readTimeoutMs;
    String currentServerAddr = serverListMgr.getCurrentServerAddr();
    int maxRetry = this.maxRetry;
    HttpClientConfig httpConfig = HttpClientConfig.builder().setReadTimeOutMillis(Long.valueOf(readTimeoutMs).intValue()).setConTimeOutMillis(ConfigHttpClientManager.getInstance().getConnectTimeoutOrDefault(100)).build();
    do {
        try {
            Header newHeaders = Header.newInstance();
            if (headers != null) {
                newHeaders.addAll(headers);
            }
            Query query = Query.newInstance().initParams(paramValues);
            HttpRestResult<String> result = NACOS_RESTTEMPLATE.get(getUrl(currentServerAddr, path), httpConfig, newHeaders, query, String.class);
            if (isFail(result)) {
                LOGGER.error("[NACOS ConnectException] currentServerAddr: {}, httpCode: {}", serverListMgr.getCurrentServerAddr(), result.getCode());
            } else {
                // Update the currently available server addr
                serverListMgr.updateCurrentServerAddr(currentServerAddr);
                return result;
            }
        } catch (ConnectException connectException) {
            LOGGER.error("[NACOS ConnectException httpGet] currentServerAddr:{}, err : {}", serverListMgr.getCurrentServerAddr(), connectException.getMessage());
        } catch (SocketTimeoutException socketTimeoutException) {
            LOGGER.error("[NACOS SocketTimeoutException httpGet] currentServerAddr:{}, err : {}", serverListMgr.getCurrentServerAddr(), socketTimeoutException.getMessage());
        } catch (Exception ex) {
            LOGGER.error("[NACOS Exception httpGet] currentServerAddr: " + serverListMgr.getCurrentServerAddr(), ex);
            throw ex;
        }
        if (serverListMgr.getIterator().hasNext()) {
            currentServerAddr = serverListMgr.getIterator().next();
        } else {
            maxRetry--;
            if (maxRetry < 0) {
                throw new ConnectException("[NACOS HTTP-GET] The maximum number of tolerable server reconnection errors has been reached");
            }
            serverListMgr.refreshCurrentServerAddr();
        }
    } while (System.currentTimeMillis() <= endTime);
    LOGGER.error("no available server");
    throw new ConnectException("no available server");
}
Also used : HttpClientConfig(com.alibaba.nacos.common.http.HttpClientConfig) SocketTimeoutException(java.net.SocketTimeoutException) Header(com.alibaba.nacos.common.http.param.Header) Query(com.alibaba.nacos.common.http.param.Query) SocketTimeoutException(java.net.SocketTimeoutException) NacosException(com.alibaba.nacos.api.exception.NacosException) ConnectException(java.net.ConnectException) ConnectException(java.net.ConnectException)

Example 4 with Header

use of com.alibaba.nacos.common.http.param.Header in project nacos by alibaba.

the class NamingHttpClientProxy method callServer.

/**
 * Call server.
 *
 * @param api       api
 * @param params    parameters
 * @param body      body
 * @param curServer ?
 * @param method    http method
 * @return result
 * @throws NacosException nacos exception
 */
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;
    String namespace = params.get(CommonParams.NAMESPACE_ID);
    String group = params.get(CommonParams.GROUP_NAME);
    String serviceName = params.get(CommonParams.SERVICE_NAME);
    params.putAll(getSecurityHeaders(namespace, group, serviceName));
    Header header = NamingHttpUtil.builderHeader();
    String url;
    if (curServer.startsWith(HTTPS_PREFIX) || curServer.startsWith(HTTP_PREFIX)) {
        url = curServer + api;
    } else {
        if (!InternetAddressUtil.containsPort(curServer)) {
            curServer = curServer + InternetAddressUtil.IP_PORT_SPLITER + serverPort;
        }
        url = NamingHttpClientManager.getInstance().getPrefix() + curServer + api;
    }
    try {
        HttpRestResult<String> restResult = nacosRestTemplate.exchangeForm(url, header, Query.newInstance().initParams(params), body, method, String.class);
        end = System.currentTimeMillis();
        MetricsMonitor.getNamingRequestMonitor(method, url, String.valueOf(restResult.getCode())).observe(end - start);
        if (restResult.ok()) {
            return restResult.getData();
        }
        if (HttpStatus.SC_NOT_MODIFIED == restResult.getCode()) {
            return StringUtils.EMPTY;
        }
        throw new NacosException(restResult.getCode(), restResult.getMessage());
    } catch (Exception e) {
        NAMING_LOGGER.error("[NA] failed to request", e);
        throw new NacosException(NacosException.SERVER_ERROR, e);
    }
}
Also used : Header(com.alibaba.nacos.common.http.param.Header) NacosException(com.alibaba.nacos.api.exception.NacosException) NacosException(com.alibaba.nacos.api.exception.NacosException)

Example 5 with Header

use of com.alibaba.nacos.common.http.param.Header in project nacos by alibaba.

the class NamingHttpUtil method builderHeader.

/**
 * Build header.
 *
 * @return header
 */
public static Header builderHeader() {
    Header header = Header.newInstance();
    header.addParam(HttpHeaderConsts.CLIENT_VERSION_HEADER, VersionUtils.version);
    header.addParam(HttpHeaderConsts.USER_AGENT_HEADER, VersionUtils.getFullClientVersion());
    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;
}
Also used : Header(com.alibaba.nacos.common.http.param.Header)

Aggregations

Header (com.alibaba.nacos.common.http.param.Header)33 InputStream (java.io.InputStream)6 NacosException (com.alibaba.nacos.api.exception.NacosException)5 HttpClientConfig (com.alibaba.nacos.common.http.HttpClientConfig)5 Query (com.alibaba.nacos.common.http.param.Query)5 Test (org.junit.Test)5 HttpRestResult (com.alibaba.nacos.common.http.HttpRestResult)3 ConnectException (java.net.ConnectException)3 SocketTimeoutException (java.net.SocketTimeoutException)3 Map (java.util.Map)3 HttpEntity (org.apache.http.HttpEntity)3 Http (com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Http)2 BaseHttpMethod (com.alibaba.nacos.common.http.BaseHttpMethod)2 IOException (java.io.IOException)2 URL (java.net.URL)2 HashMap (java.util.HashMap)2 HttpRequestBase (org.apache.http.client.methods.HttpRequestBase)2 NacosLoadException (com.alibaba.nacos.api.exception.runtime.NacosLoadException)1 JdkHttpClientResponse (com.alibaba.nacos.common.http.client.response.JdkHttpClientResponse)1 Cluster (com.alibaba.nacos.naming.core.Cluster)1