Announcement Announcement Module
Collapse
No announcement yet.
Sending POST parameters with RestTemplate requests Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Sending POST parameters with RestTemplate requests

    I'm trying out Spring 3.0's RestTemplate.

    I'm trying to send POST parameters along with my request, but can't figure out how to do that. Judging from the documentation, the FormHttpMessageConverter can:
    read and write form data from the HTTP request and response. By default, this converter reads and writes the media type application/x-www-form-urlencoded. Form data is read from and written into a MultiValueMap<String, String>.
    I understand how I can register these http message converters in the RestTemplate, but can't seem to figure out how to add POST parameters when doing the request. Apparently I need a MultiValueMap<String,String>, and it's easy enough to create one. However, where do I use this map?

    I've tried the generic 'execute' methods in RestTemplate, and create a RequestCallback, but I can't add the POST parameters there either.

    Any ideas?

  • #2
    you can do it like this:

    Code:
    public void post(){
    		MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    		map.add("name", "xx");
    		map.add("password", "xx");
    		String result = rest.postForObject("http://localhost:8080/soa-server/user/", map, String.class);
    		System.out.println(result);
    	}

    and before you use resttemplate you must init it :
    Code:
    RestTemplate rest = new RestTemplate();
    	
    
    		HttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
    		HttpMessageConverter stringHttpMessageConverternew = new StringHttpMessageConverter();
    		rest.setMessageConverters(new HttpMessageConverter[]{formHttpMessageConverter, stringHttpMessageConverternew});


    my english is not very good , sorry. I do not know can you understand me
    Last edited by oakeye; Nov 24th, 2009, 07:40 PM.

    Comment


    • #3
      great!

      Originally posted by oakeye View Post
      my english is not very good , sorry. I do not know can you understand me
      Yes, I can understand you. and it's helpful!

      Comment


      • #4
        Thanks oakeye! very useful post.

        Comment


        • #5
          A Complete Spring Client sample using RestTemplate?

          Can someone point me to where I can get a simple but complete Spring web client (consumer of Web Services) sample app?

          I am using Spring 3, Hibernate 3, all available Annotations (java).

          Thanks.

          Comment


          • #6
            RestTemplate - Mixing Parameters in MultivalueMap

            Oakeye, i understand your example, but i have a question... can i do this:

            Code:
            public void post(@RequestParam("file") MultiPartFile pFile){
            
               MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
               map.add("name", "xx");
               map.add("password", "xx");
               map.add("file", pFile);
            
            String result = rest.postForObject("http://localhost:8080/soa-server/user/", map, String.class);
            		System.out.println(result);
            	}
            I mean... can i mix string parameters with a multipartfile type parameters to send it using RestTemplate? How can i do that?

            Thanks!

            Comment


            • #7
              Code:
              @RequestMapping("/file")
              public class FileController {
              	
              	@RequestMapping(value = "/upload" , method = RequestMethod.POST)
              	@ResponseBody
              	public String upload(@RequestParam() MultipartFile file, HttpServletResponse response) throws Exception {
              		String path = FileController.class.getResource("/").getPath().split("WEB-INF")[0]
              				+ "upload/"; // 获取站点下的绝对磁盘路径
              		String fileName = file.getOriginalFilename().split("\\.")[0];
              //		String filePath = path + fileName + ".xls ";
              		String filePath = path + fileName;
              		System.out.println(path);
              		byte[] bytes;
              		FileOutputStream fos = null;
              		System.out.println("上传文件开始");
              		try {
              			bytes = file.getBytes();
              			fos = new FileOutputStream(filePath);
              			fos.write(bytes); 
              		} catch (IOException e) {
              			e.printStackTrace();
              		} finally{
              			fos.close();
              		}
              		JSONObject json = JsonMessage.loadSuccess();
              		
              		json.put("msg", fileName);
              		
              		return json.toString();
              	}

              Comment


              • #8
                Sending POST parameters with RestTemplate requests

                Oakeye, thanks for your response.

                That is not working for me, i am getting a convertion exception all the time.

                Here is the stacktrace...
                Code:
                org.springframework.http.converter.HttpMessageNotWritableException: Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.web.multipart.commons.CommonsMultipartFile]
                	at org.springframework.http.converter.FormHttpMessageConverter.writePart(FormHttpMessageConverter.java:292)
                	at org.springframework.http.converter.FormHttpMessageConverter.writeParts(FormHttpMessageConverter.java:252)
                	at org.springframework.http.converter.FormHttpMessageConverter.writeMultipart(FormHttpMessageConverter.java:242)
                	at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:194)
                	at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:1)
                	at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:588)
                	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:436)
                	at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:415)
                	at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:294)
                	at com.yoostar.admintool.web.UploadTestController.create(UploadTestController.java:86)
                	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
                	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
                	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
                	at java.lang.reflect.Method.invoke(Method.java:597)
                	at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
                	at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
                	at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
                	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:774)
                	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
                	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
                	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
                	at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
                	at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
                	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
                	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
                	at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
                	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
                	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
                	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
                	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
                	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
                	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
                	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
                	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
                	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
                	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
                	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
                	at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
                	at java.lang.Thread.run(Thread.java:619)
                As example, i'm using this on both sides....

                Client side (Web app that consumes rest services throught RestTemplate).

                Code:
                // Here uploadItem is a DTO that contain a MultipartFile as a member.
                @RequestMapping(method = RequestMethod.POST)
                    public String create(UploadDTO uploadItem, BindingResult result) throws IOException {
                
                
                
                	if (result.hasErrors()) {
                	    for (ObjectError error : result.getAllErrors()) {
                		System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
                	    }
                	    return "uploadtest/upload";
                	}
                
                	MultiValueMap<String, Object> variablesMap = new LinkedMultiValueMap<String, Object>();
                	variablesMap.add("file", uploadItem.getFileData());
                	
                	Map<String, Object> wsResponse = super.getRestTemplate().postForObject(postUpload, variablesMap, Map.class);
                	
                	if (!wasSuccesfulCall(wsResponse)) {
                	    throw getServiceExceptionFromWSResponse(wsResponse);
                	}
                
                	Map<String, Object> beanMap = this.getData(wsResponse);
                	
                	return "redirect:/uploadtest/show";
                    }
                On the other side....(Another Web app with rest services implemented with Spring).

                Code:
                 @RequestMapping(value = "/UploadTestFile", method = { RequestMethod.POST })
                    public ModelAndView getFile(@RequestParam() MultipartFile file, HttpServletResponse response) {
                	DateFormat sdf = new SimpleDateFormat("ddMMyyyyhhMMss");
                	File f = new File("C:/tempFile-" + sdf.format(new Date()) + ".jpg");
                	
                	if (file == null) {
                	    System.out.println("file null .. exit...");    
                	    return null;
                	}
                        ...
                }

                By the way... is working for you?... can you share an example?.
                It seems that i have to code a CommonsMultipartHttpMessageConverter...

                Any suggestion?.

                Thanks again!.

                Comment


                • #9
                  Sending POST parameters with RestTemplate requests

                  Oakeye, thanks for your response.

                  That is not working for me, i am getting a convertion exception all the time.

                  Here is the stacktrace...
                  Code:
                  org.springframework.http.converter.HttpMessageNotWritableException: Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.web.multipart.commons.CommonsMultipartFile]
                  	at org.springframework.http.converter.FormHttpMessageConverter.writePart(FormHttpMessageConverter.java:292)
                  	at org.springframework.http.converter.FormHttpMessageConverter.writeParts(FormHttpMessageConverter.java:252)
                  	at org.springframework.http.converter.FormHttpMessageConverter.writeMultipart(FormHttpMessageConverter.java:242)
                  	at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:194)
                  	at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:1)
                  	at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:588)
                  	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:436)
                  	at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:415)
                  	at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:294)
                  	at com.yoostar.admintool.web.UploadTestController.create(UploadTestController.java:86)
                  	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
                  	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
                  	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
                  	at java.lang.reflect.Method.invoke(Method.java:597)
                  	at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
                  	at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
                  	at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
                  	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:774)
                  	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
                  	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
                  	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
                  	at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
                  	at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
                  	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
                  	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
                  	at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
                  	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
                  	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
                  	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
                  	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
                  	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
                  	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
                  	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
                  	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
                  	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
                  	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
                  	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
                  	at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
                  	at java.lang.Thread.run(Thread.java:619)
                  As example, i'm using this on both sides....

                  Client side (Web app that consumes rest services throught RestTemplate).


                  Code:
                  // Here uploadItem is a DTO that contain a MultipartFile as a member.
                  @RequestMapping(method = RequestMethod.POST)
                      public String create(UploadDTO uploadItem, BindingResult result) throws IOException {
                  
                  
                  
                  	if (result.hasErrors()) {
                  	    for (ObjectError error : result.getAllErrors()) {
                  		System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
                  	    }
                  	    return "uploadtest/upload";
                  	}
                  
                  	MultiValueMap<String, Object> variablesMap = new LinkedMultiValueMap<String, Object>();
                  	variablesMap.add("file", uploadItem.getFileData());
                  	
                  	Map<String, Object> wsResponse = super.getRestTemplate().postForObject(postUpload, variablesMap, Map.class);
                  	
                  	if (!wasSuccesfulCall(wsResponse)) {
                  	    throw getServiceExceptionFromWSResponse(wsResponse);
                  	}
                  
                  	Map<String, Object> beanMap = this.getData(wsResponse);
                  	
                  	return "redirect:/uploadtest/show";
                      }
                  On the other side....(Another Web app with rest services implemented with Spring).

                  Code:
                   @RequestMapping(value = "/UploadTestFile", method = { RequestMethod.POST })
                      public ModelAndView getFile(@RequestParam() MultipartFile file, HttpServletResponse response) {
                  	DateFormat sdf = new SimpleDateFormat("ddMMyyyyhhMMss");
                  	File f = new File("C:/tempFile-" + sdf.format(new Date()) + ".jpg");
                  	
                  	if (file == null) {
                  	    System.out.println("file null .. exit...");    
                  	    return null;
                  	}
                          ...
                  }

                  By the way... is working for you?... can you share an example?.
                  It seems that i have to code a CommonsMultipartHttpMessageConverter...

                  Any suggestion?.

                  Thanks again!.

                  Comment


                  • #10
                    please add
                    Code:
                    	<!-- 文件上传 -->
                    	<bean id="multipartResolver"  
                            class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
                            <property name="maxUploadSize">  
                                <value>104857600</value>  
                            </property>  
                            <property name="maxInMemorySize">  
                                <value>4096</value>  
                            </property>      
                    	</bean>
                    in your applicationContext.xml

                    Comment


                    • #11
                      Sending Multipart File as POST parameters with RestTemplate requests

                      Oakeye, thanks for your response again.

                      That configuration is already on my application-context.xml.

                      I have:

                      Code:
                      <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
                              <property name="maxUploadSize" value="${maxUploadSize}"/>
                      </bean>
                      Code:
                      <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
                      		<constructor-arg ref="httpClientFactory" />
                      		<property name="messageConverters">
                      			<list>
                      				<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
                      				<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
                      				<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
                      			</list>
                      		</property>
                      </bean>
                      But i still having no luck with the rest template. I will post an example of what a have in my project as soon as possible.

                      Btw, what do you think that i missing?
                      For the message of the exception that i getting:

                      Code:
                      Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.web.multipart.commons.CommonsMultipartFile]
                      I think that i need an special converter. Something like an MultipartConverter...

                      Comment


                      • #12
                        I do not know what is wrong with you.

                        I will give you a demo later.

                        I am so busy today.

                        Comment


                        • #13
                          Sending Multipart File as POST parameters with RestTemplate requests

                          Hi Oakeye,

                          I'm posting an (non working :P) example project with the configuration that i am using for post multifileparts through Rest Template.
                          It would be nice if you can check what i am missing?

                          To show the upload form, deploy the application and put this URL: http://localhost:8080/sites/postupload

                          Thanks again!.
                          Regards.
                          Mauro.

                          Comment


                          • #14
                            my applicationContext.xml
                            Code:
                            <?xml version="1.0" encoding="UTF-8"?>
                            <beans xmlns="http://www.springframework.org/schema/beans"
                            	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                            	xmlns:context="http://www.springframework.org/schema/context"
                            	xmlns:aop="http://www.springframework.org/schema/aop"
                            	xmlns:tx="http://www.springframework.org/schema/tx"
                            	xsi:schemaLocation="
                            		http://www.springframework.org/schema/beans
                            		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                            		http://www.springframework.org/schema/context
                            		http://www.springframework.org/schema/context/spring-context-3.0.xsd
                            		http://www.springframework.org/schema/aop
                            		http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                            		http://www.springframework.org/schema/tx
                            		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
                            
                            	<!-- 数据库配置,使用dbcp连接池 
                            	<bean id="dataSource"
                            		class="org.apache.commons.dbcp.BasicDataSource"
                            		destroy-method="close">
                            		<property name="driverClassName"
                            			value="${jdbc.driverClassName}" />
                            		<property name="url" value="${jdbc.url}" />
                            		<property name="username" value="${jdbc.username}" />
                            		<property name="password" value="${jdbc.password}" />
                            	</bean>
                            	
                            	 事务管理器配置,单数据源事务 
                            	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                            		<property name="dataSource" ref="dataSource" />
                            	</bean>
                            
                            	 使用annotation定义事务 
                            	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
                            	<context:property-placeholder location="/WEB-INF/jdbc.properties" />
                            	<context:component-scan base-package="com.***.dao" />
                            	-->
                            	<context:component-scan base-package="com.***.service" />
                            	
                            	<!-- 文件上传 -->
                            	<bean id="multipartResolver"  
                                    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
                                    <property name="maxUploadSize">  
                                        <value>104857600</value>  
                                    </property>  
                                    <property name="maxInMemorySize">  
                                        <value>4096</value>  
                                    </property>      
                            	</bean>  
                            
                            </beans>

                            Comment


                            • #15
                              springmvc-servlet.xml
                              Code:
                              <?xml version="1.0" encoding="UTF-8"?>
                              <beans xmlns="http://www.springframework.org/schema/beans"
                              	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                              	xmlns:p="http://www.springframework.org/schema/p"
                              	xmlns:context="http://www.springframework.org/schema/context"
                              	xmlns:mvc="http://www.springframework.org/schema/mvc"
                              	
                              	xsi:schemaLocation="
                              		http://www.springframework.org/schema/beans
                              		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                              		http://www.springframework.org/schema/context
                              		http://www.springframework.org/schema/context/spring-context-3.0.xsd
                              		http://www.springframework.org/schema/mvc
                              		http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
                              	<context:component-scan
                              		base-package="com.***.controller" />
                              		
                              	<!-- Dispatches requests mapped to POJO @Controllers implementations -->
                              	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
                              		<property name="messageConverters">
                              			<list>
                              				<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
                              				<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
                              				<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
                              				<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
                              			</list>
                              		</property>
                              	</bean>
                              	
                              	<mvc:annotation-driven/>
                              	
                              </beans>

                              Comment

                              Working...
                              X