java调用http api接口(java创建http接口及调用)
1.修改web.xml文件
- <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.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 com.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();
- }
,
免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com