Page 1 of 2 12 LastLast
Results 1 to 10 of 19

Thread: Sending POST parameters with RestTemplate requests

  1. #1
    Join Date
    Sep 2009
    Location
    Leiden, The Netherlands
    Posts
    9

    Default 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. #2
    Join Date
    Nov 2009
    Posts
    15

    Default

    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 at 06:40 PM.

  3. #3
    Join Date
    Dec 2007
    Location
    Boston, MA
    Posts
    34

    Talking great!

    Quote 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!

  4. #4
    Join Date
    Aug 2004
    Location
    Norwalk, CT USA
    Posts
    27

    Default

    Thanks oakeye! very useful post.
    Ritesh

  5. #5

    Default 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.

  6. #6
    Join Date
    Jul 2008
    Posts
    18

    Default 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!

  7. #7
    Join Date
    Nov 2009
    Posts
    15

    Default

    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();
    	}

  8. #8
    Join Date
    Jul 2008
    Posts
    18

    Question 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!.

  9. #9
    Join Date
    Jul 2008
    Posts
    18

    Question 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!.

  10. #10
    Join Date
    Nov 2009
    Posts
    15

    Default

    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

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •