首页 \ 问答 \ 有没有好的java自学网站?java自学资料

有没有好的java自学网站?java自学资料

更新时间:2021-12-04 15:12

最满意答案

定义一个简单的restful接口 @RestController public class TestController { @RequestMapping(value = "testPost", method = RequestMethod.POST) public ResponseBean testPost(@RequestBody RequestBean requestBean) { ResponseBean responseBean = new ResponseBean(); responseBean.setRetCode("0000"); responseBean.setRetMsg("succ"); return responseBean; } } 使用RestTemplate访问该服务 //请求地址 String url = ""; //入参 RequestBean requestBean = new RequestBean(); requestBean.setTest1("1"); requestBean.setTest2("2"); requestBean.setTest3("3"); RestTemplate restTemplate = new RestTemplate(); ResponseBean responseBean = restTemplate.postForObject(url, requestBean, ResponseBean.class); 从这个例子可以看出,使用restTemplate访问restful接口非常的简单粗暴无脑。(url, requestMap, ResponseBean.class)这三个参数分别代表 请求地址、请求参数、HTTP响应转换被转换成的对象类型。 RestTemplate方法的名称遵循命名约定,第一部分指出正在调用什么HTTP方法,第二部分指示返回的内容。本例中调用了restTemplate.postForObject方法,post指调用了HTTP的post方法,Object指将HTTP响应转换为您选择的对象类型。还有其他很多类似的方法,有兴趣的同学可以参考官方api。 三.手动指定转换器(HttpMessageConverter) 我们知道,调用reseful接口传递的数据内容是json格式的字符串,返回的响应也是json格式的字符串。然而restTemplate.postForObject方法的请求参数RequestBean和返回参数ResponseBean却都是java类。是RestTemplate通过HttpMessageConverter自动帮我们做了转换的操作。 默认情况下RestTemplate自动帮我们注册了一组HttpMessageConverter用来处理一些不同的contentType的请求。 如StringHttpMessageConverter来处理text/plain;MappingJackson2HttpMessageConverter来处理application/json;MappingJackson2XmlHttpMessageConverter来处理application/xml。 你可以在org.springframework.http.converter包下找到所有spring帮我们实现好的转换器。 如果现有的转换器不能满足你的需求,你还可以实现org.springframework.http.converter.HttpMessageConverter接口自己写一个。详情参考官方api。 选好了HttpMessageConverter后怎么把它注册到我们的RestTemplate中呢。 RestTemplate restTemplate = new RestTemplate(); //获取RestTemplate默认配置好的所有转换器 List> messageConverters = restTemplate.getMessageConverters(); //默认的MappingJackson2HttpMessageConverter在第7个 先把它移除掉 messageConverters.remove(6); //添加上GSON的转换器 messageConverters.add(6, new GsonHttpMessageConverter()); 这个简单的例子展示了如何使用GsonHttpMessageConverter替换掉默认用来处理application/json的MappingJackson2HttpMessageConverter。 四.设置底层连接方式 要创建一个RestTemplate的实例,您可以像上述例子中简单地调用默认的无参数构造函数。这将使用java.NET包中的标准Java类作为底层实现来创建HTTP请求。 但很多时候我们需要像传统的HttpClient那样设置HTTP请求的一些属性。RestTemplate使用了一种很偷懒的方式实现了这个需求,那就是直接使用一个HttpClient作为底层实现...... //生成一个设置了连接超时时间、请求超时时间、异常最大重试次数的httpClient RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(10000).setSocketTimeout(30000).build(); HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(config).setRetryHandler(new DefaultHttpRequestRetryHandler(5, false)); HttpClient httpClient = builder.build(); //使用httpClient创建一个ClientHttpRequestFactory的实现 ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); //ClientHttpRequestFactory作为参数构造一个使用作为底层的RestTemplate RestTemplate restTemplate = new RestTemplate(requestFactory); 五.设置拦截器(ClientHttpRequestInterceptor) 有时候我们需要对请求做一些通用的拦截设置,这就可以使用拦截器进行处理。拦截器需要我们实现org.springframework.http.client.ClientHttpRequestInterceptor接口自己写。 举个简单的例子,写一个在header中根据请求内容和地址添加令牌的拦截器。 public class TokenInterceptor implements ClientHttpRequestInterceptor { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { //请求地址 String checkTokenUrl = request.getURI().getPath(); //token有效时间 int ttTime = (int) (System.currentTimeMillis() / 1000 + 1800); //请求方法名 POST、GET等 String methodName = request.getMethod().name(); //请求内容 String requestBody = new String(body); //生成令牌 此处调用一个自己写的方法,有兴趣的朋友可以自行google如何使用ak/sk生成token,此方法跟本教程无关,就不贴出来了 String token = TokenHelper.generateToken(checkTokenUrl, ttTime, methodName, requestBody); //将令牌放入请求header中 request.getHeaders().add("X-Auth-Token",token); return execution.execute(request, body); } } 创建RestTemplate实例的时候可以这样向其中添加拦截器 RestTemplate restTemplate = new RestTemplate(); //向restTemplate中添加自定义的拦截器 restTemplate.getInterceptors().add(new TokenInterceptor());

其他回答

一、css代码的次序不对 或许在你的印象中,css是无序的,可以随意掺插,其实这种想法是错误的。如果你的css代码含有多个相同的属性,但每一个属性都有不同的值,那么浏览器会选择哪个呢?譬如: body{background-color:red} body{background-col...

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)