使用RestTemplate发送post请求

简介: 最近使用RestTemplate发送post请求,遇到了很多问题,如转换httpMessage失败、中文乱码等,调了好久才找到下面较为简便的方法: RestTemplate restTemplate = new RestTemplate(); HttpHeaders head...

最近使用RestTemplate发送post请求,遇到了很多问题,如转换httpMessage失败、中文乱码等,调了好久才找到下面较为简便的方法:

RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        
        JSONObject jsonObj = JSONObject.fromObject(params);
        
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);

        String result = restTemplate.postForObject(url, formEntity, String.class);

如果直接使用在postForObject中把对象传入很容易出现no suitable HttpMessageConverter found for request type的错误,建议直接先转成字符串,见jsonObj.otString(),
网上有人说设置RestTemplate的HttpMessageConverter,试了一下要引入各种包。
另外要注意中文编码问题,网上有人说StringHttpMessageConverter默认使用ISO-8859-1,要指定为UTF-8编码,自己尝试没有成功,最后通过指定contentType的方式解决了。

 

http://liuxing.info/2015/05/21/RestTemplate实践/

http://www.cnblogs.com/zemliu/archive/2013/07/28/3220517.html

 

 /**
        *
        * This is going to setup the REST server configuration in the applicationContext
        * you can see that I am using the new Spring's Java Configuration style and not some OLD XML file
        *
        */
       ApplicationContext context = new AnnotationConfigApplicationContext(RESTConfiguration.class);

       /**
        *
        * We now get a RESTServer bean from the ApplicationContext which has all the data we need to
        * log into the REST service with.
        *
        */
       RESTServer mRESTServer = context.getBean(RESTServer.class);

       /**
        *
        * Setting up BASIC Authentication access
        *
        */

        HttpClient client = new HttpClient();
       UsernamePasswordCredentials credentials =
               new UsernamePasswordCredentials(mRESTServer.getUser(), mRESTServer.getPassword());

       client.getState().setCredentials(
               new AuthScope(mRESTServer.getHost(), 8080, AuthScope.ANY_REALM),
               credentials);

       CommonsClientHttpRequestFactory commons = new CommonsClientHttpRequestFactory(client);



       /**
        *
        * Setting up data to be sent to REST service
        *
        */
       Map<String, String> vars = new HashMap<String, String>();
       vars.put("id", "INID");

       /**
        *
        * Doing the REST call and then displaying the data/user object
        *
        */
       try
       {

           /*

               This is code to post and return a user object

            */

           RestTemplate rt = new RestTemplate(commons); // Added the CommonsClientHttpRequestFactory

           rt.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
           rt.getMessageConverters().add(new StringHttpMessageConverter());

           String uri = new String("http://" + mRESTServer.getHost() + ":8080/springmvc-resttemplate-auth-test/api/{id}");

           User u = new User();
           u.setName("Johnathan M Smith");
           u.setUser("JMS");


           User returns = rt.postForObject(uri, u, User.class, vars);

           LOGGER.debug("User:  " + u.toString());

https://github.com/JohnathanMarkSmith/springmvc-resttemplate-auth-test

        /**
         *
         * This is going to setup the REST server configuration in the applicationContext
         * you can see that I am using the new Spring's Java Configuration style and not some OLD XML file
         *
         */
        ApplicationContext context = new AnnotationConfigApplicationContext(RESTConfiguration.class);

        /**
         *
         * We now get a RESTServer bean from the ApplicationContext which has all the data we need to
         * log into the REST service with.
         *
         */
        RESTServer mRESTServer = context.getBean(RESTServer.class);



        /**
         *
         * Setting up data to be sent to REST service
         *
         */
        Map<String, String> vars = new HashMap<String, String>();
        vars.put("id", "JS01");




        /**
         *
         * Doing the REST call and then displaying the data/user object
         *
         */


        try
        {

            /*

                This is code to post and return a user object

             */

            RestTemplate rt = new RestTemplate();
            rt.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
            rt.getMessageConverters().add(new StringHttpMessageConverter());

            String uri = new String("http://" + mRESTServer.getHost() + ":8080/springmvc-resttemplate-test/api/{id}");

            User u = new User();
            u.setName("Johnathan M Smith");
            u.setUser("JS01");


            User returns = rt.postForObject(uri, u, User.class, vars);
            LOGGER.debug("User:  " + u.toString());

https://github.com/JohnathanMarkSmith/springmvc-resttemplate-test

 

相关文章
|
Linux iOS开发 MacOS
typora下载和破解(仅供学习)
Typora 一款 Markdown 编辑器和阅读器 风格极简 / 多种主题 / 支持 macOS,Windows 及 Linux 实时预览 / 图片与文字 / 代码块 / 数学公式 / 图表 目录大纲 / 文件管理 / 导入与导出 ……
163036 11
typora下载和破解(仅供学习)
|
JSON Java API
玩转Spring Boot之RestTemplate的使用
在java代码里想要进行restful web client服务,一般使用Apache的HttpClient。不过此种方法使用起来太过繁琐。Spring Boot提供了一种简单便捷的内置模板类来进行操作,这就是RestTemplate。
5959 0
|
Java Maven
【笔记04】下载、配置 MAVEN(配置 MAVEN 本地仓库)(MAVEN 的 setting.xml)
下载、配置 MAVEN(配置 MAVEN 本地仓库)(MAVEN 的 setting.xml)
6098 1
【笔记04】下载、配置 MAVEN(配置 MAVEN 本地仓库)(MAVEN 的 setting.xml)
|
12月前
|
搜索推荐 安全
如果您干不动跨境外贸独立站,可以来看看反向海淘代购模式
反向海淘代购模式是指海外消费者通过国内电商平台购买中国商品,再由代购方负责采购、质检、包装和国际运输。该模式商品丰富、价格竞争力强,能满足个性化需求,但也面临物流成本高、海关政策复杂等挑战。
|
网络协议
IPv6 私有地址
IPv6 私有地址
2073 0
IPv6 私有地址
|
Java 数据库 索引
【Java】已解决Spring框架中的org.springframework.dao.DuplicateKeyException异常
【Java】已解决Spring框架中的org.springframework.dao.DuplicateKeyException异常
535 0
|
消息中间件 JavaScript 小程序
SpringBoot 多数据源及事务解决方案 上
SpringBoot 多数据源及事务解决方案 上
SpringBoot 多数据源及事务解决方案  上
免费顺丰快递单号查询电子面单api接口对接
顺丰速运快递查询接口API和电子面单接口怎么对接?除了通过顺丰自己的接口对接外,用的最多的就是第三方通过快递鸟对接了,通过顺丰单号和手机号后四位查询轨迹信息,如果是通过快递鸟下单获得的顺丰单号,可通过单号直接查询,具体下载快递鸟接口技术文档查看接口说明。
8472 0
|
JSON 编解码 Java
小白一看就会的Spring的RestTemplate的使用
您好,我是码农飞哥,感谢您阅读此文。作为一名Java开发者,我们怎么都绕不开调用外部接口的场景,调用的方式要么是通过Http协议来调用,要么是通过RPC协议来调用,通过Http协议调用的话我们就需要用到Http的Api。比较常用的有Apache的HttpClient和原生的HttpURLConnection。这些Api都比较好用,但是我们今天要介绍一种更加好用API,Spring自带的RestTemplate,能力更强,使用更方便。
759 0
小白一看就会的Spring的RestTemplate的使用

热门文章

最新文章