最近在研究spring3.0以及传说中的restful,还好研究出来一个例子,现在贴出来望广大网友能一起讨论下,错误的地方恳请大家指点。项目采用SPRING3.0+HIBERNATE2.5。数据库是oracle只有一个表。
- create table LMDZ
- (
- KH_NUM VARCHAR2(20 ),
- LM_NUM NUMBER(2 )
- );
首先在eclipse下新建web工程。web.xml文件配置如下:
- <?xml version= "1.0" encoding= "UTF-8" ?>
- <web-app version="2.5" xmlns= "http://java.sun.com/xml/ns/javaee" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" >
- <!--
- 该servlet为tomcat,jetty等容器提供,将静态资源映射从/改为/static /目录,如原来访问
- http://localhost/foo.css ,现在http://localhost/static/foo.css
- -->
- <servlet-mapping>
- <servlet-name>default </servlet-name>
- <url-pattern>/static /*</url-pattern>
- </servlet-mapping>
- <servlet>
- <servlet-name>demorestsms</servlet-name>
- <servlet-class >org.springframework.web.servlet.DispatcherServlet</servlet- class >
- <load-on-startup>1 </load-on-startup>
- </servlet>
- <!--
- Key of the system property that should specify the root directory of this
- web app. Applied by WebAppRootListener or Log4jConfigListener.
- -->
- <context-param>
- <param-name>webAppRootKey</param-name>
- <param-value>demorestsms.root</param-value>
- </context-param>
- <!--
- Location of the Log4J config file, for initialization and refresh checks.
- Applied by Log4jConfigListener.
- -->
- <context-param>
- <param-name>log4jConfigLocation</param-name>
- <param-value>/WEB-INF/classes/log4j.properties</param-value>
- </context-param>
- <!--
- - Location of the XML file that defines the root application context.
- - Applied by ContextLoaderServlet.
- -
- - Can be set to:
- - "/WEB-INF/applicationContext-hibernate.xml" for the Hibernate implementation,
- - "/WEB-INF/applicationContext-jpa.xml" for the JPA one, or
- - "/WEB-INF/applicationContext-jdbc.xml" for the JDBC one.
- -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/applicationContext.xml</param-value>
- <!--
- <param-value>/WEB-INF/applicationContext-hibernate.xml</param-value>
- <param-value>/WEB-INF/applicationContext-jpa.xml</param-value>
- -->
- <!--
- To use the JPA variant above, you will need to enable Spring load-time
- weaving in your server environment. See PetClinic's readme and/or
- Spring's JPA documentation for information on how to do this .
- -->
- </context-param>
- <!--
- - Configures Log4J for this web app.
- - As this context specifies a context-param "log4jConfigLocation" , its file path
- - is used to load the Log4J configuration, including periodic refresh checks.
- -
- - Would fall back to default Log4J initialization (non-refreshing) if no special
- - context-params are given.
- -
- - Exports a "web app root key" , i.e. a system property that specifies the root
- - directory of this web app, for usage in log file paths.
- - This web app specifies "petclinic.root" (see log4j.properties file).
- -->
- <!-- Leave the listener commented-out if using JBoss -->
- <!--
- <listener>
- <listener-class >org.springframework.web.util.Log4jConfigListener</listener- class >
- </listener>
- -->
- <!--
- - Loads the root application context of this web app at startup,
- - by default from "/WEB-INF/applicationContext.xml" .
- - Note that you need to fall back to Spring's ContextLoaderServlet for
- - J2EE servers that do not follow the Servlet 2.4 initialization order.
- -
- - Use WebApplicationContextUtils.getWebApplicationContext(servletContext)
- - to access it anywhere in the web application, outside of the framework.
- -
- - The root context is the parent of all servlet-specific contexts.
- - This means that its beans are automatically available in these child contexts,
- - both for getBean(name) calls and (external) bean references.
- -->
- <listener>
- <listener-class >org.springframework.web.context.ContextLoaderListener</listener- class >
- </listener>
- <!--
- - Maps the petclinic dispatcher to "*.do" . All handler mappings in
- - petclinic-servlet.xml will by default be applied to this subpath.
- - If a mapping isn't a /* subpath, the handler mappings are considered
- - relative to the web app root.
- -
- - NOTE: A single dispatcher can be mapped to multiple paths, like any servlet.
- -->
- <servlet-mapping>
- <servlet-name>zszqrestsms</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- <session-config>
- <session-timeout>10 </session-timeout>
- </session-config>
- <welcome-file-list>
- <!-- Redirects to "welcome.htm" for dispatcher handling -->
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <!--error-page>
- <exception-type>java.lang.Exception</exception-type>
- <location>/WEB-INF/jsp/uncaughtException.jsp</location>
- </error-page-->
- <!-- 浏览器不支持put,delete等method,由该filter将/blog?_method=delete转换为标准的http delete方法 -->
- <filter>
- <filter-name>HiddenHttpMethodFilter</filter-name>
- <filter-class >org.springframework.web.filter.HiddenHttpMethodFilter</filter- class >
- </filter>
- <filter-mapping>
- <filter-name>HiddenHttpMethodFilter</filter-name>
- <servlet-name>demorestsms</servlet-name>
- </filter-mapping>
- </web-app>
在WEB-INF下面的applicationContext.xml文件如下:
- <?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:tx="http://www.springframework.org/schema/tx" xmlns:jdbc= "http://www.springframework.org/schema/jdbc"
- xmlns:p="http://www.springframework.org/schema/p"
- 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/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/jdbc
- http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">
- <bean id="propertyConfigurer"
- class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
- p:location="/WEB-INF/jdbc.properties" />
- <bean id="dataSource"
- class = "org.springframework.jdbc.datasource.DriverManagerDataSource"
- p:driverClassName="${jdbc.driverClassName}"
- p:url="${jdbc.url}"
- p:username="${jdbc.username}"
- p:password="${jdbc.password}" />
- <!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
- <!-- Hibernate SessionFactory -->
- <bean id="sessionFactory" class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean"
- p:dataSource-ref="dataSource" p:mappingResources= "zszqlmdz.hbm.xml" >
- <property name="hibernateProperties" >
- <props>
- <prop key="hibernate.dialect" >${hibernate.dialect}</prop>
- <prop key="hibernate.show_sql" >${hibernate.show_sql}</prop>
- <prop key="hibernate.generate_statistics" >${hibernate.generate_statistics}</prop>
- </props>
- </property>
- <property name="eventListeners" >
- <map>
- <entry key="merge" >
- <bean class = "org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener" />
- </entry>
- </map>
- </property>
- </bean>
- <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
- <bean id="transactionManager" class = "org.springframework.orm.hibernate3.HibernateTransactionManager"
- p:sessionFactory-ref="sessionFactory" />
- <!-- Transaction manager that delegates to JTA (for a transactional JNDI DataSource) -->
- <!--
- <bean id="transactionManager" class = "org.springframework.transaction.jta.JtaTransactionManager" />
- -->
- <!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= -->
- <!--
- Activates various annotations to be detected in bean classes:
- Spring's @Required and @Autowired, as well as JSR 250' s @Resource .
- -->
- <context:annotation-config/>
- <!--
- Instruct Spring to perform declarative transaction management
- automatically on annotated classes.
- -->
- <tx:annotation-driven/>
- <!--
- Exporter that exposes the Hibernate statistics service via JMX. Autodetects the
- service MBean, using its bean name as JMX object name.
- -->
- <context:mbean-export/>
- <!-- PetClinic's central data access object: Hibernate implementation -->
- <bean id="clinic" class = "com.cssweb.zszq.lmdz.hibernate.HibernateClinic" />
- <!-- Hibernate's JMX statistics service -->
- <bean name="demorestsms:type=HibernateStatistics" class = "org.hibernate.jmx.StatisticsService" autowire= "byName" />
- </beans>
在WEB-INF下面的demorestsms-servlet.xml文件如下:
- <?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:p= "http://www.springframework.org/schema/p"
- xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc= "http://www.springframework.org/schema/jdbc"
- 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/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/jdbc
- http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">
- <!--
- - The controllers are autodetected POJOs labeled with the @Controller annotation.
- -->
- <context:component-scan base-package = "com.cssweb.zszq.lmdz.web" />
- <!--
- - The form-based controllers within this application provide @RequestMapping
- - annotations at the type level for path mapping URLs and @RequestMapping
- - at the method level for request type mappings (e.g., GET and POST).
- - In contrast, ClinicController - which is not form-based - provides
- - @RequestMapping only at the method level for path mapping URLs.
- -
- - DefaultAnnotationHandlerMapping is driven by these annotations and is
- - enabled by default with Java 5 +.
- -->
- <bean class = "org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
- <!--
- - This bean processes annotated handler methods, applying PetClinic-specific PropertyEditors
- - for request parameter binding. It overrides the default AnnotationMethodHandlerAdapter.
- -->
- <bean class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
- <property name="webBindingInitializer" >
- <bean class = "com.cssweb.zszq.lmdz.web.ClinicBindingInitializer" />
- </property>
- </bean>
- <!--
- - This bean resolves specific types of exceptions to corresponding logical
- - view names for error views. The default behaviour of DispatcherServlet
- - is to propagate all exceptions to the servlet container: this will happen
- - here with all other types of exceptions.
- -->
- <bean class = "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" >
- <property name="exceptionMappings" >
- <props>
- <prop key="org.springframework.dao.DataAccessException" >dataAccessFailure</prop>
- <prop key="org.springframework.transaction.TransactionException" >dataAccessFailure</prop>
- </props>
- </property>
- </bean>
- <!--
- - This bean configures the 'prefix' and 'suffix' properties of
- - InternalResourceViewResolver, which resolves logical view names
- - returned by Controllers. For example, a logical view name of "vets"
- - will be mapped to "/WEB-INF/jsp/vets.jsp" .
- -->
- <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix= "/WEB-INF/jsp/"
- p:suffix=".jsp" />
- <!--
- - Message source for this context, loaded from localized "messages_xx" files.
- - Could also reside in the root application context, as it is generic,
- - but is currently just used within PetClinic's web tier.
- -->
- <bean id="messageSource" class = "org.springframework.context.support.ResourceBundleMessageSource"
- p:basename="messages" />
- </beans>
在WEB-INF下面的jdbc.properties文件如下:
- # To change this template, choose Tools | Templates
- # and open the template in the editor.
- jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
- jdbc.url=jdbc:oracle:thin:@localhost : 1521 :orcl
- jdbc.username=scott
- jdbc.password=tiger
- hibernate.generate_statistics=true
- hibernate.show_sql=true
- hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
配置大致就这些,下面给出连接hibernate的接口
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package com.cssweb.zszq.lmdz;
- import java.util.Collection;
- import org.springframework.dao.DataAccessException;
- import com.cssweb.zszq.lmdz.pojo.Khzl;
- import com.cssweb.zszq.lmdz.pojo.LmdzNew;
- /**
- *
- * @author HUJUN
- */
- public interface Clinic {
- Collection<LmdzNew> findLmdzs(String fundid) throws DataAccessException;
- void save(String fundid, String[] no) throws DataAccessException;
- int delete(String fundid) throws DataAccessException;
- Khzl findKh(String clientId) throws DataAccessException;
- int updateTelById(String fundid, String mobile) throws DataAccessException;
- }
连接hibernate的service类
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package com.cssweb.zszq.lmdz.hibernate;
- import java.util.Collection;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.transaction.annotation.Transactional;
- import com.cssweb.zszq.lmdz.Clinic;
- import com.cssweb.zszq.lmdz.pojo.Khzl;
- import com.cssweb.zszq.lmdz.pojo.LmdzNew;
- /**
- *
- * @author HUJUN
- */
- public class HibernateClinic implements Clinic {
- @Autowired
- private SessionFactory sessionFactory;
- @Transactional (readOnly = true )
- @SuppressWarnings ( "unchecked" )
- public Collection<LmdzNew> findLmdzs(String fundid) {
- return sessionFactory.getCurrentSession().createQuery( "from LmdzNew lmdz where lmdz.khNum = :fundid" )
- .setString("fundid" , fundid).list();
- }
- public void save(String fundid, String[] no) {
- Session session = sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
- for ( int i = 0 ; i < no.length; i++) {
- LmdzNew lmdzNes = new LmdzNew(fundid, Integer.parseInt(no[i]));
- session.save(lmdzNes);
- if (i % 20 == 0 ) {
- session.flush();
- session.clear();
- }
- }
- tx.commit();
- session.close();
- }
- public int delete(String fundid) {
- return sessionFactory.openSession().createQuery( "delete from LmdzNew lmdz where lmdz.khNum = :fundid" )
- .setString("fundid" , fundid).executeUpdate();
- }
- @Transactional (readOnly = true )
- public Khzl findKh(String clientId) {
- return (Khzl) sessionFactory.openSession().load(Khzl. class , clientId);
- }
- public int updateTelById(String fundid, String mobile) {
- return sessionFactory.openSession().createQuery( "update Khzl set mobileTel = :mobile where clientId = :fundid" )
- .setString("fundid" , fundid)
- .setString("mobile" , mobile)
- .executeUpdate();
- }
- }
再来看action这一层的东西:
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package com.cssweb.zszq.lmdz.web;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import java.util.Collection;
- import java.util.Iterator;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import com.cssweb.common.util.CollectionData;
- import com.cssweb.zszq.lmdz.Clinic;
- import com.cssweb.zszq.lmdz.pojo.Khzl;
- import com.cssweb.zszq.lmdz.pojo.LmdzNew;
- /**
- *
- * @author HUJUN
- */
- @Controller
- @RequestMapping ( "/zszqsms" )
- public class LmdzForm {
- private final Clinic clinic;
- @Autowired
- public LmdzForm(Clinic clinic) {
- this .clinic = clinic;
- }
- @RequestMapping (value= "/{fundid}" , method = RequestMethod.GET)
- public void get(HttpServletRequest request, HttpServletResponse response, @PathVariable ( "fundid" ) String fundid) throws Exception {
- System.out.println(">>>>>>>>>>getList>>>>>>>>>>>>>>" +fundid);
- StringBuilder msg = new StringBuilder();
- Khzl khzl = this .clinic.findKh(fundid);
- if (khzl!= null ) {
- Collection<LmdzNew> lm = CollectionData.getLmList();
- Collection<LmdzNew> results = this .clinic.findLmdzs(fundid);
- Iterator<LmdzNew> it = lm.iterator();
- String json = "{total:" +lm.size()+ ",root:[" ;
- int i = 0 ;
- while (it.hasNext()) {
- LmdzNew lmdz = it.next();
- lmdz.setState(1 );
- json += "{lmid:'" + lmdz.getLmNum() + "',lmname:'" + lmdz.getLmName() + "',lmstate:'" + lmdz.getState() + "'}" ;
- i++;
- if (i != lm.size() - 1 ) {
- json += "," ;
- }
- }
- json += "]}" ;
- msg.append("{/" msg/ ":/" "+json+" / "}" );
- }
- else {
- msg.append("{/" msg/ ":/" 帐号不存在/ "}" );
- }
- printData(response, msg);
- }
- @RequestMapping (value = "/{fundid}/{no}" , method = RequestMethod.POST)
- public void save(HttpServletRequest request, HttpServletResponse response, @PathVariable ( "fundid" ) String fundid,
- @PathVariable ( "no" ) String no) throws Exception {
- System.out.println(fundid + ">>>>>>>>>>save>>>>>>>>>>>>>>" +no);
- StringBuilder msg = new StringBuilder();
- this .clinic.save(fundid, no.split( "," ));
- msg.append("{/" msg/ ":/" 成功/ "}" );
- printData(response, msg);
- }
- @RequestMapping (value = "/{fundid}/{no}" , method = RequestMethod.PUT)
- public void update(HttpServletRequest request, HttpServletResponse response, @PathVariable ( "fundid" ) String fundid,
- @PathVariable ( "no" ) String no) throws Exception {
- System.out.println(fundid + ">>>>>>>>>>update>>>>>>>>>>>>>>" +no);
- StringBuilder msg = new StringBuilder();
- int i = this .clinic.updateTelById(fundid, no);
- if (i> 0 ) {
- msg.append("{/" msg/ ":/" 成功/ "}" );
- }
- msg.append("{/" msg/ ":/" 失败/ "}" );
- printData(response, msg);
- }
- @RequestMapping (value = "/{fundid}" , method = RequestMethod.DELETE)
- public void delete(HttpServletRequest request, HttpServletResponse response, @PathVariable ( "fundid" ) String fundid)
- throws Exception {
- System.out.println(">>>>>>>>>>delete>>>>>>>>>>>>>>" +fundid);
- StringBuilder msg = new StringBuilder();
- int i = this .clinic.delete(fundid);
- if (i> 0 ) {
- msg.append("{/" msg/ ":/" 成功/ "}" );
- }
- msg.append("{/" msg/ ":/" 失败/ "}" );
- printData(response, msg);
- }
- private void printData(HttpServletResponse response, StringBuilder msg){
- try {
- response.setContentType("text/html;charset=utf-8" );
- response.setCharacterEncoding("UTF-8" );
- PrintWriter out = new PrintWriter( new OutputStreamWriter(response.getOutputStream(), "UTF-8" ));
- out.println( msg );
- out.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
最后还有个POJO类,呵呵:
- package com.cssweb.zszq.lmdz.pojo;
- /**
- * LmdzNew entity. @author MyEclipse Persistence Tools
- */
- public class LmdzNew implements java.io.Serializable {
- // Fields
- /**
- *
- */
- private static final long serialVersionUID = -5138845755309588033L;
- private String khNum;
- private int lmNum;
- private String lmName;
- private int state;
- // Constructors
- /** default constructor */
- public LmdzNew() {
- }
- /** full constructor */
- public LmdzNew(String khNum, int lmNum) {
- this .khNum = khNum;
- this .lmNum = lmNum;
- }
- public String getKhNum() {
- return this .khNum;
- }
- public void setKhNum(String khNum) {
- this .khNum = khNum;
- }
- public int getLmNum() {
- return this .lmNum;
- }
- public void setLmNum( int lmNum) {
- this .lmNum = lmNum;
- }
- public String getLmName() {
- return lmName;
- }
- public void setLmName(String lmName) {
- this .lmName = lmName;
- }
- public int getState() {
- return state;
- }
- public void setState( int state) {
- this .state = state;
- }
- public boolean equals(Object other) {
- if (( this == other))
- return true ;
- if ((other == null ))
- return false ;
- return false ;
- }
- public int hashCode() {
- int result = 17 ;
- result = 37 * result
- + (getKhNum() == null ? 0 : this .getKhNum().hashCode());
- return result;
- }
- }
好了,所有的源代码都贴出来了。整个服务端的程序可以跑在tomcat下做测试。接下来我们只需要提供rest客户端的接口让别的应用调用即可。下面再给出个调用的demo。这个项目比较简单。
还望大家多多指教,大家互相学习学习。
- package com.cssweb.zszq.client;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
- public class ClientTest {
- public static void main(String[] args) throws IOException {
- delete();
- update();
- save();
- select();
- }
- /**
- * 查询栏目定制
- * 68008610为资金帐号
- */
- public static void select() {
- try {
- URL url = new URL( "http://localhost:8080/zszqrestsms/zszqsms/68008610" );
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setDoOutput(true );
- conn.setRequestMethod("GET" );
- conn.setRequestProperty("Content-Type" , "text/json" );
- BufferedReader rd = new BufferedReader( new InputStreamReader(conn
- .getInputStream()));
- String line;
- while ((line = rd.readLine()) != null ) {
- System.out.println(line);
- }
- rd.close();
- } catch (Exception e) {
- System.out.println("Error" + e);
- }
- }
- /**
- * 删除定制栏目
- * 68008610为资金帐号
- */
- public static void delete() {
- try {
- URL url = new URL( "http://localhost:8080/zszqrestsms/zszqsms/68008610" );
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setDoOutput(true );
- conn.setRequestMethod("DELETE" );
- conn.setRequestProperty("Content-Type" , "text/json" );
- BufferedReader rd = new BufferedReader( new InputStreamReader(conn
- .getInputStream()));
- String line;
- while ((line = rd.readLine()) != null ) {
- System.out.println(line);
- }
- rd.close();
- } catch (Exception e) {
- System.out.println("Error" + e);
- }
- }
- /**
- * 修改手机号码
- * 68008610为资金帐号
- */
- public static void update() {
- try {
- URL url = new URL( "http://localhost:8080/zszqrestsms/zszqsms/68008610/1342345677" );
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setDoOutput(true );
- conn.setRequestMethod("PUT" );
- conn.setRequestProperty("Content-Type" , "text/json" );
- BufferedReader rd = new BufferedReader( new InputStreamReader(conn
- .getInputStream()));
- String line;
- while ((line = rd.readLine()) != null ) {
- System.out.println(line);
- }
- rd.close();
- } catch (Exception e) {
- System.out.println("Error" + e);
- }
- }
- /**
- * 保存定制的栏目
- * 68008610为资金帐号
- */
- public static void save() {
- try {
- URL url = new URL( "http://localhost:8080/zszqrestsms/zszqsms/68008617/1,2,3,4" );
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setDoOutput(true );
- conn.setRequestMethod("POST" );
- conn.setRequestProperty("Content-Type" , "text/json" );
- BufferedReader rd = new BufferedReader( new InputStreamReader(conn
- .getInputStream()));
- String line;
- while ((line = rd.readLine()) != null ) {
- System.out.println(line);
- }
- rd.close();
- } catch (Exception e) {
- System.out.println("Error" + e);
- }
- }
- }