當前位置:編程學習大全網 - 源碼下載 - java如何創建壹個簡單的http接口?

java如何創建壹個簡單的http接口?

1.修改web.xml文件

<!-- 模擬HTTP的調用,寫的壹個.atoz..atoz..atoz.action.order.SendSMSAction; import com.atoz.util.SpringContextUtil;

public class SmsHTTPServer extends HttpServlet { private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); String content = request.getParameter("content"); //String content = new String(request.getParameter("content").getBytes("iso-8859-1"), "utf-8"); String mobiles = request.getParameter("mobiles"); String businesscode = request.getParameter("businesscode"); String businesstype = request.getParameter("businesstype"); if (content == null || "".equals(content) || content.length() <= 0) { System.out.println("http call failed,參數content不能為空,程序退出"); } else if (mobiles == null || "".equals(mobiles) || mobiles.length() <= 0) { System.out.println("http call failed,參數mobiles不能為空,程序退出"); } else { /*SendSMSServiceImpl send = new SendSMSServiceImpl();*/ SendSMSAction sendSms = (SendSMSAction) SpringContextUtil.getBean("sendSMS"); sendSms.sendSms(content, mobiles, businesscode, businesstype); System.out.println("---http call success---"); } out.close(); }

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }

3.調用http接口

String content = "測試"; content = URLEncoder.encode(content, "utf-8"); String url = "http://localhost:8180/atoz_2014/httpServer?content=" + content + "&mobiles=15301895007"; URL httpTest; try { httpTest = new URL(url); BufferedReader in; try { in = new BufferedReader(new InputStreamReader( httpTest.openStream())); String inputLine = null; String resultMsg = null; //得到返回信息的xml字符串 while ((inputLine = in.readLine()) != null) if(resultMsg != null){ resultMsg += inputLine; }else { resultMsg = inputLine; } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }

打字不易,望采納,謝謝

  • 上一篇:什麽是審計報告?
  • 下一篇:股票知識:超跌區該如何認定
  • copyright 2024編程學習大全網