GVKun编程网logo

RestTemplate(resttemplate post请求参数)

12

在本文中,我们将给您介绍关于RestTemplate的详细内容,并且为您解答resttemplatepost请求参数的相关问题,此外,我们还将为您提供关于Anerrorhappenedduringte

在本文中,我们将给您介绍关于RestTemplate的详细内容,并且为您解答resttemplate post请求参数的相关问题,此外,我们还将为您提供关于An error happened during template parsing (template: "class path resource [templates/index.h...、Angular 学习系列 - - $templateCache 和 $templateRequest、HTTL模板getTemplate()报错java.lang.IllegalStateException: Not found template /***.httl in ClasspathResource、http调用之RestTemplate的知识。

本文目录一览:

RestTemplate(resttemplate post请求参数)

RestTemplate(resttemplate post请求参数)

一、

@Component
public class HelpUtil {

public static String getData(String url) throws ClientProtocolException,
URISyntaxException, IOException {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("utf-8")));
String rspMsg = restTemplate.getForObject(url,
String.class);
return rspMsg;
}

public static ResponseBean getByPostData(String url,Map<String,Object> params) throws ClientProtocolException,
URISyntaxException, IOException {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/x-www-form-urlencoded");
MultiValueMap<String, Object> requestEntity = new LinkedMultiValueMap<>();
for (String key:params.keySet()) {
requestEntity.add(key,String.valueOf( params.get(key)));
}
HttpEntity<MultiValueMap<String, Object>> r = new HttpEntity<>(
requestEntity, headers);
ResponseBean rspMsg = restTemplate.postForObject(url,r , ResponseBean.class);
return rspMsg;

}

public static String getStrByPostData(String url,Map<String,Object> params) throws ClientProtocolException,
URISyntaxException, IOException {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/x-www-form-urlencoded");
MultiValueMap<String, Object> requestEntity = new LinkedMultiValueMap<>();
for (String key:params.keySet()) {
requestEntity.add(key,String.valueOf( params.get(key)));
}
HttpEntity<MultiValueMap<String, Object>> r = new HttpEntity<>(
requestEntity, headers);
String rspMsg = restTemplate.postForObject(url,r , String.class);
return rspMsg;

}

}
二、
public String getToken(){
try {
String resultContent= HelpUtil.getData(tokenUrl);
Map<String, Object> resultMap = JSON.parseObject(resultContent,
new TypeReference<Map<String, Object>>() {
});
Integer code = (Integer) resultMap.get("code");
if(code==0){
String dataJson = resultMap.get("data").toString();
Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
Integer expriesIn = (Integer) dataMap.get("expriesIn");
String accessToken = (String) dataMap.get("accessToken");
return accessToken;
}else{
log.info("得到token报错->"+resultMap.toString());
}
}catch (Exception e){
log.error("得到token报错->{}",e);
return null;
}
return null;
}

public String getLastTime(String accessToken,String mobile){
try {
Map<String,Object> params=new HashMap<String,Object>();
params.put("accessToken",accessToken);
params.put("mobile",mobile);
String resultContent= HelpUtil.getStrByPostData(detail_url,params);
Map<String, Object> resultMap = JSON.parseObject(resultContent,
new TypeReference<Map<String, Object>>() {
});
Integer code = (Integer) resultMap.get("code");
if(code==0 && null!=resultMap.get("data")){
String dataJson = resultMap.get("data").toString();
Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
if(null!=dataMap.get("lastLoginTime")){
String lastTime= dataMap.get("lastLoginTime").toString();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long lt = new Long(lastTime);
Date date = new Date(lt);
String dateFmt = simpleDateFormat.format(date);
return dateFmt;
}
}else{
log.info("得到lastTime报错->"+resultMap.toString());
}
}catch (Exception e){
log.error("得到lastTime报错->{}",e);
return null;
}
return null;
}

An error happened during template parsing (template:

An error happened during template parsing (template: "class path resource [templates/index.h...

转自 https://blog.csdn.net/qq_41426326/article/details/88837112

在开发 springboot 的时候,进行 modelAndView 视图层映射的时候,一直出现 

An error happened during template parsing (template: "class path resource [templates/index.html]")

模板解析过程中发生错误 (模板:“类路径资源 [templates/index.html]”)

在向 index.html 映射的时候出现错误,小编在和其他程序员一样打开了百度开始搜索,有各种说法

1. 配置文件问题.(我重新看了一遍确定没有问题,但是还是错误)

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.encoding=utf-8
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.cache=false
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/static/
2. 说是 @Controller 和 @RestController 功能不一样,将 @Controller 修改为 @RestController 在加上 @ResponseBody (依然无效)、

3. 说在映射的时候实体类没有 get 方法,为变量加上 get 就可以了(结果我本来就有 get 方法的)

4. 还有说在 pom.xml 文件下的 build 配置 (都不是这个错误的解决方案)

<resources>
<resource>
<directory>sre/main/resources</directory>
</resource>
</resources>
最后小编早上智商最高峰的时候发现了这个小小小问题

 

在这附上小编 index.html 的文件开头,就是因为加了

https: xmlns:https="http://www.w3.org/1999/xhtml"

xmlns:th="http://www.thymeleaf.org"
导致调用的时候原本要调用第二句话的代码调用了第一句代码中的方法发生错误,把第一句代码删除就可以了

小编总结了一下,一般系统出现以下错误

An error happened during template parsing (template: "class path resource [templates/index.html]")

大家可以去看看视图层,并不是 java 代码出现错误.

Angular 学习系列 - - $templateCache 和 $templateRequest

Angular 学习系列 - - $templateCache 和 $templateRequest

OSC 请你来轰趴啦!1028 苏州源创会,一起寻宝 AI 时代

$templateCache

第一次使用模板,它被加载到模板缓存中,以便快速检索。你可以直接将模板标签加载到缓存中,或者通过 $templateCache 服务。

通过 script 标签

<script type=”text/ng-template” id=”template.html”>

<p>This is the content of the template</p>

</script>

备注:script 标签模板不需要包含在文档头部。但他必须在 $rootElement 下,不然模板将会被忽略。

通过 $templateCache 服务:

<div ng-app="Demo" ng-controller="testCtrl as ctrl"><!--<div ng-include="''templateId.html''"></div>--><div ng-bind-html="ctrl.text"></div>
  </div>

(function () {
    angular.module("Demo", [])
    .run(["$templateCache",templateCache])
    .controller("testCtrl", ["$templateCache","$sce",testCtrl]);function templateCache($templateCache){
      $templateCache.put(''templateId.html''''<a>This is the content of the template</a>'');
    }function testCtrl($templateCache,$sce) {var tpl = $templateCache.get(''templateId.html'');
        tpl = $sce.trustAsHtml(tpl);this.text = tpl;
    };
  }());

在上面调用模板的代码中,可以使用 controller 里的代码调用缓存里的模板,但是需要注意的是,需要使用 $sce 转成受信任的 html 插入代码,所以这里需要注入 $sce 服务。而且这边不止可以使用 js 调用,也可以直接在 html 里标签里使用 ng-include 调用。

$templateRequest

$templateRequest 服务运行进行安全检测,然后使用 $http 下载被提供的模板,成功后,将内容存储在 $templateCache 里。如果 HTTP 请求失败或 HTTP 请求的响应数据是空的,将抛出个 $compile 错误(通过设置该函数的第二个参数为 true)。该注意的是,$templateCache 的内容是可信的,所以调用 $sce.getTrustedUrl (tpl) 是省略的,当 tpl 的类型是字符串并且 $templateCache 具有匹配的项。

使用:$templateRequest(tpl,[ignoreRequestError]);

tpl:字符串或者 TrustedResourceUrl,HTTP 请求 URL 的模板。

ignoreRequestError:boolean 值,当请求失败或模板为空时,是否忽略该异常。

使用代码:

(function () {
    angular.module("Demo", [])
    .run(["$templateCache",templateCache])
    .controller("testCtrl", ["$templateRequest","$sce",testCtrl]);function templateCache($templateCache){
      $templateCache.put(''templateId.html''''<a>This is the content of the template</a>'');
    }function testCtrl($templateRequest,$sce) {var vm = this;
        $templateRequest("templateId.html").then(function(html){
            vm.text = $sce.trustAsHtml(html);
        })
    };
  }());

HTTL模板getTemplate()报错java.lang.IllegalStateException: Not found template /***.httl in ClasspathResource

HTTL模板getTemplate()报错java.lang.IllegalStateException: Not found template /***.httl in ClasspathResource

使用HTTL的Engine方法getTemplate 报模板没有没到

Engine engine = Engine.getEngine("conf/httl.properties");

Template template = engine.getTemplate("pullFail.httl")// 这里报错


java.lang.IllegalStateException: Not found template /pullFail.httl in ClasspathResource
    at httl.spi.loaders.resources.AbstractResource.getSource(AbstractResource.java:87)
    at httl.spi.engines.DefaultEngine.parseTemplate(DefaultEngine.java:248)
    at httl.spi.engines.DefaultEngine.getTemplate(DefaultEngine.java:233)
    at httl.Engine.getTemplate(Engine.java:333)
   
Caused by: java.io.FileNotFoundException: Not found template /pullFail.httl in ClasspathResource
    at httl.spi.loaders.resources.InputStreamResource.openReader(InputStreamResource.java:56)
    at httl.spi.loaders.resources.AbstractResource.getSource(AbstractResource.java:85)
    ... 61 common frames omitted

我的配置文件和模板文件都在resources目录下的子目录里

配置文件在conf下

forbid.methods=
template.directory=httl/
template.suffix=.httl
comment.left=/*
comment.right=*/
reloadable=true
output.stream=false
output.writer=true
precompiled=true
input.encoding=UTF-8
output.encoding=UTF-8

模板文件在httl下

 

配置文件都可以读取到,模板文件却找不到

模板文件各种命中都试过了

/***.httl  httl/***.httl    /httl/***.httl   ./***.httl

 

烦请知道的朋友指点下

http调用之RestTemplate

http调用之RestTemplate

核心方法为org.springframework.web.client.RestTemplate.doExecute(URI, HttpMethod, RequestCallback, ResponseExtractor<T>)

方法内容如下:

 

 其中,重点在下面这三行

 

 ClientHttpRequest是http请求调用的抽象,具体实现有jdk自带的以及apache的httpclient,实现类如下:

 

simple开头的是使用jdk自带的net操作,Components的底层是httpclient操作。

 AbstractBufferingClientHttpRequest为缓存requestbody的基类,内部bufferedOutput保存了requestbody的内容,避免流的二次读取会导致读取不到数据。

那么,到底是哪里给这个ByteArrayOutputStream对象赋值的呢?答案就在org.springframework.web.client.RestTemplate.HttpEntityRequestCallback,注释讲得很清楚:

 

 在上面讲到的重点强调的三行代码中,调用了org.springframework.web.client.RestTemplate.HttpEntityRequestCallback.doWithRequest(ClientHttpRequest)方法,这个方法里面根据requestContentType等信息,在HttpMessageConverters列表中寻找合适的HttpMessageConverter,利用这些httpMessageConverter天然的write方法将requestBody的内容经过处理转换写入入参HttpOutputMessage对应的getBody方法返回的OutputStream流中。然而,我们这里的ClientHttpRequest接口继承自HttpOutputMessage,AbstractClientHttpRequest的getBody实现调用子类的getBodyInternal方法,重点来了,AbstractBufferingClientHttpRequest的getBodyInternal返回的就是bufferedOutput,也就是缓存的ByteArrayOutputStream。到这里,缓存的requestbody数据有了。再啰嗦一句,使用HttpEntityRequestCallback的都是post请求的,get请求用的AcceptHeaderRequestCallback。

那么,问题来了,什么情况下会用这个缓存数据呢?我们看下AbstractBufferingClientHttpRequest的子类就知道了。

这里,又要回到刚刚的三行重点代码,doExecute的时候调用createRequest方法返回ClientHttpRequest,实际调用父类方法org.springframework.http.client.support.HttpAccessor.createRequest(URI, HttpMethod):

 

 

 org.springframework.http.client.support.InterceptingHttpAccessor.getRequestFactory()方法如下:

 

 

 如果设置了拦截器就返回InterceptingClientHttpRequestFactory,并将restTemplete原有的RequestFactory作为参数传入。

该factory创建的是org.springframework.http.client.InterceptingClientHttpRequest,该类重写的executeInternal方法通过内部类InterceptingRequestExecution实现interceptors顺序执行,当迭代结束后,通过之前传进来的requestFactory创建ClientHttpRequest,并将body copy给刚刚创建的request的body,并调用execute方法,方法内容如下:

其实,InterceptingClientHttpRequest本身就带有requestbody缓存copy功能,所以无需在创建restTemplate时包装一个BufferingClientHttpRequestFactory,直接使用HttpComponentsClientHttpRequestFactory即可,这个factory自带bufferRequestBody功能。

相信大部分同学在项目中都是选择apache的httpclient发送http请求,所以,这里我们重点看下org.springframework.http.client.HttpComponentsClientHttpRequestFactory,我们看下createRequest方法:

public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
        HttpClient client = getHttpClient();

        HttpUriRequest httpRequest = createHttpUriRequest(httpMethod, uri);
        postProcessHttpRequest(httpRequest);
        HttpContext context = createHttpContext(httpMethod, uri);
        if (context == null) {
            context = HttpClientContext.create();
        }

        // Request configuration not set in the context
        if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
            // Use request configuration given by the user, when available
            RequestConfig config = null;
            if (httpRequest instanceof Configurable) {
                config = ((Configurable) httpRequest).getConfig();
            }
            if (config == null) {
                config = createRequestConfig(client);
            }
            if (config != null) {
                context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);
            }
        }
     // 默认情况下bufferRequestBody为true,创建使用缓存的body作为请求体
        if (this.bufferRequestBody) {
            return new HttpComponentsClientHttpRequest(client, httpRequest, context);
        }
        else {
            return new HttpComponentsStreamingClientHttpRequest(client, httpRequest, context);
        }
    }

看下上面注释的类的下面方法org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpHeaders, byte[]):

 

 

 这个类也是继承自AbstractBufferingClientHttpRequest,所以刚刚InterceptingRequestExecution迭代结束后getBody返回的就是缓存的bufferedOutput,到这里执行的时候就将bufferedOutput作为ByteArrayEntity发送http请求。至此,结束。

 

今天的关于RestTemplateresttemplate post请求参数的分享已经结束,谢谢您的关注,如果想了解更多关于An error happened during template parsing (template: "class path resource [templates/index.h...、Angular 学习系列 - - $templateCache 和 $templateRequest、HTTL模板getTemplate()报错java.lang.IllegalStateException: Not found template /***.httl in ClasspathResource、http调用之RestTemplate的相关知识,请在本站进行查询。

本文标签: