java如何写一个接口?

java如何写一个接口?,第1张

非常简单,基础语法:

public interface 接口名 {

常量定义

抽象方法定义;

default 方法定义;

}

即使你在接口中不定义任何方法,也是可以的。

1.修改web.xml文件

<!-- 模拟HTTP的调用,写的一个http接口 --><servlet><servlet-name>TestHTTPServer</servlet-name><servlet-class>com.atoz.http.SmsHTTPServer</servlet-class></servlet><servlet-mapping><servlet-name>TestHTTPServer</servlet-name><url-pattern>/httpServer</url-pattern></servlet-mapping>

2.新建SmsHTTPServer.java文件

package com.atoz.http

import java.io.IOExceptionimport java.io.PrintWriter

import javax.servlet.ServletExceptionimport javax.servlet.http.HttpServletimport javax.servlet.http.HttpServletRequestimport javax.servlet.http.HttpServletResponse

import com.atoz.action.order.SendSMSActionimport 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/htmlcharset=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 = nullString 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 blocke.printStackTrace() }

打字不易,望采纳,谢谢


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/8108450.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-13
下一篇 2023-04-13

发表评论

登录后才能评论

评论列表(0条)

保存