对Spring MVC Controller的Java HTTP POST请求

时间:2014-01-08 10:10:31

标签: java http spring-mvc post httprequest

我有一个带有以下方法定义的Spring MVC控制器:

@RequestMapping(value="SaveReading.htm",method=RequestMethod.POST)
protected void saveReading(Reading reading) throws ServletException, IOException {
    logger.debug("Received reading for id: " + reading.getMonitorId());
}

我需要通过生成POST HTTP请求从Java程序向此控制器发送数据。

我尝试了以下代码:

try {

    url = new URL("http://localhost:8080/WebApp/SaveReading.htm");
} catch (MalformedURLException e) {
    logger.error("Malformed URL ", e);
    return;
}
try {
    conn = (HttpURLConnection)url.openConnection();
    logger.debug("Opened Connection. " + conn.getURL());
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.connect();

    writer = new OutputStreamWriter(conn.getOutputStream());        
} catch (IOException e) {
    logger.error("Error setting up URL connection: ", e);
}

String data = "";
try {
    data = URLEncoder.encode("monitorId", "UTF-8") + "=" + URLEncoder.encode(id, "UTF-8");
    data += "&" + URLEncoder.encode("timeStamp", "UTF-8") + "=" + URLEncoder.encode(""+new Date().getTime(), "UTF-8");
} catch (UnsupportedEncodingException e) {
    logger.error("Encoding problem ", e);
}
System.out.println("Sending HTTP message: \n" + data);
// Send data
try {
    writer.write(data);
    writer.flush();

Java代码无法访问控制器。 我正在使用的URL是正确的,假设我的Web项目是“WebApp”吗?

  • web.xml

    <display-name>Web Application</display-name>  
    
    <servlet>  
        <servlet-name>ReadingsServlet</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    
    <servlet-mapping>  
        <servlet-name>ReadingsServlet</servlet-name>  
        <url-pattern>*.htm</url-pattern>  
    </servlet-mapping>  
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/ReadingsServlet-servlet.xml
        </param-value>
    </context-param>
    
  • ReadingsServlet-servlet.xml

    <context:annotation-config />
    <context:component-scan base-package="com.myapp.familycare"/>
    
    <context:component-scan base-package="miscillaneous.property_placeholder" /> 
    
    <mvc:annotation-driven />
    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    

1 个答案:

答案 0 :(得分:0)

现在确实有效。 我不确定是什么原因引起了这个问题。