servlet使用

1、配置文件

web.xml里:

<servlet>
     <servlet-name>GetTicketNotify</servlet-name>
     <servlet-class>ctais.business.tsrj.wxyy.api.GetTicketNotify</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>GetTicketNotify</servlet-name>
      <url-pattern>/GetTicketNotify</url-pattern>
  </servlet-mapping>

2、接口类:

package ctais.business.tsrj.wxyy.api;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import ctais.business.common.remote.core.Service;
import ctais.business.tsrj.common.util.LeakUtil;
import ctais.services.log.LogManager;
import ctais.services.xml.XMLDataObject;
import ctais.util.StringEx;

public class GetTicketNotify extends HttpServlet{
	/**
	 * 接口
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Constructor of the object.
	 */
	public GetTicketNotify() {
		super();
	}
	public void destroy() {
		super.destroy(); 
	}
	public void init() throws ServletException {
	}
	@Override
	protected void doGet(HttpServletRequest request,HttpServletResponse response){
		doPost(request,response);
	}
	@Override
	protected void doPost(HttpServletRequest request,HttpServletResponse response){
		try {
			//获取json传参
			StringBuffer str = new StringBuffer(); 
			try {
				   BufferedInputStream in = new BufferedInputStream(request.getInputStream());
				      int i;
				      char c;
				      while ((i=in.read())!=-1) {
				      c=(char)i;
				      str.append(c);
				      }
				     }catch (Exception ex) {
				    	 LogManager.getLogger().error("接收参数失败。。");
				   ex.printStackTrace();
				   }
			System.out.println(str);
	        JSONObject obj= JSONObject.fromObject(str.toString());
	        //从json获取参数
	        LogManager.getLogger().info("接收参数:"+obj);
	        String aptid =  obj.getString("aptid");
			String ticketno =  obj.getString("ticketno");
			String tickettime = obj.getString("tickettime");
			System.out.println("aptid:"+aptid+"  ticketno:"+ticketno+"  tickettime:"+tickettime);
			//转换参数为xml格式
			StringBuffer sb = new StringBuffer("<ROOT><APTID>");
	        sb.append(aptid);
	        sb.append("</APTID><TICKETNO>");
	        sb.append(ticketno);
	        sb.append("</TICKETNO><TICKETTIME>");
	        sb.append(tickettime);
	        sb.append("</TICKETTIME></ROOT>");
			Service coreSrv = new Service("tsrj.wxyy.api.ForOuterService.GetTicketNotify");
		    XMLDataObject xml = coreSrv.doService(sb.toString());//获取运行结果
		    System.out.println( xml.asXML().toString());
		    String errcode = LeakUtil.esSQM(StringEx.sNull(xml.getItemValue("ERRCODE")));
		    JSONObject jsonObject = new JSONObject();//返回json
		    if("0".equals(errcode)){
		    	jsonObject.put("errcode", "0");
		    }else{
		    	jsonObject.put("errcode", "1");
		    	jsonObject.put("errmsg", "failed!");
		    }
		    System.out.println(xml);
		    LogManager.getLogger().info("返回参数:"+jsonObject);
			PrintWriter out = response.getWriter();
			out.print(jsonObject);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}

3、测试调用接口类:

package ctais.business.tsrj.wxyy.api;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

public class TestClient {
	/**
     * 调用对方接口方法
     * @param path 对方或第三方提供的路径
     * @param data 向对方或第三方发送的数据,大多数情况下给对方发送JSON数据让对方解析
     */
    public static String interfaceUtil(String path,String data) {
    	String result = "";
    	try {
        	
            URL url = new URL(path);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            PrintWriter out = null;
            //请求方式
//          conn.setRequestMethod("POST");
//           //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); 
            //设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
            //最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
            //post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            //发送请求参数即数据
            out.print(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
                System.out.println(str);
            }
            result = str;
            //关闭流
            is.close();
            //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
            System.out.println("完整结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * HttpClient 处理方式
     * @param content  发送请求的内容  字符类型  TokenKey=cec084dfd89a0efe2bf742f7c98f7e8625547460&Name=anyd&Telephone=13594866323&Title=5554545&Content=ddd&Source=2&DataID=1111111111&TypeIndex=0&ImageList=2565
     * @param url    请求地址
     * @return
     * @author anyd
     */
    public static String httpClientDoPost(String url,String content){
        try {
            // 将参数转为二进制流
            byte[] requestBytes = content.getBytes("utf-8");
            HttpClient httpClient = new HttpClient();
            PostMethod postMethod = new PostMethod(url);
             // 设置请求头  Content-Type
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,
                    requestBytes.length);
            RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,
                    requestBytes.length, "application/json; charset=utf-8"); // 请求体
            postMethod.setRequestEntity(requestEntity);
            httpClient.executeMethod(postMethod);// 执行请求
            InputStream soapResponseStream = postMethod.getResponseBodyAsStream();// 获取返回的流
            byte[] datas = null;
            try {
                datas = readInputStream(soapResponseStream);// 从输入流中读取数据
            } catch (Exception e) {
                e.printStackTrace();
            }
            String result = new String(datas, "utf-8");// 将二进制流转为String
            System.out.println("!!!!!   ---   "+result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return null;
    }
    /**
     * 从输入流中读取数据
     * 
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;
    }

    public static void main(String[] args) {
    	JSONObject jsonObject = new JSONObject();
    	
    	jsonObject.put("aptid", "7198150");
    	jsonObject.put("ticketno", "000");
    	jsonObject.put("winid", "12");
    	jsonObject.put("now", "2018-08-25 10:19:00");
    	jsonObject.put("tickettime", "2018-08-25 10:19:00");
    	jsonObject.put("calltime", "2018-08-25 10:19:00");
    	jsonObject.put("cmd", "All");
    	System.out.println(jsonObject.toString());
    	
    	httpClientDoPost("http://192.168.22.96:7002/tax/GetDepIfo",jsonObject.toString() );//150.100.16.205:5001
//    	httpClientDoPost("http://192.168.22.96:7002/tax/GetTicketNotify",jsonObject.toString() );//150.100.16.205:5001
//        interfaceUtil("http://192.168.10.89:8080/eoffice-restful/resources/sys/oadata", "usercode=10012");
//        interfaceUtil("http://192.168.10.89:8080/eoffice-restful/resources/sys/oaholiday",
//                    "floor=first&year=2017&month=9&isLeader=N");
    }
}

记得导入servlet.jar,资源里已经上传。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值