servlet--http接口简单的创建及调用

          很久没有用servlet的交互技术,生疏的遭不住。现在简单的说说servlet中http接口的创建及调用,便于大家理解,使用。

先说说服务端,就是提供服务方的代码:

pom.xml

 <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
	</dependency>
    
  </dependencies>

首先是提供一个接口的代码如下:

import java.io.BufferedReader;
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;
/**
 * @author cwc
 * @date 2018年7月9日  
 * @version 1.0.0 
 * @description:创建一个Http接口
 */
public class SetInfo extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	
	protected void doGet(HttpServletRequest request,
	           HttpServletResponse response) throws ServletException, IOException {
		 //判断请求报文是否来自代维系统的ip地址
	       String ip = request.getRemoteHost();
	       // 获取收到的报文
	        BufferedReader reader = request.getReader();
	         String line = "";
	        StringBuffer inputString = new StringBuffer();
	        while ((line = reader.readLine()) != null) {
	        inputString.append(line);
	        System.out.println("接受到的数据"+line);
	        }
	        
	       //如有必要,可以在报文中增加其他验证和加密的参数
	       //解析获取到的报文,根据ip地址、其他验证、加密等等来判断请求报文的服务器是否有权限
	       //如果请求验证合格,则根据请求的参数装配返回的报文
	 
	       // 要返回的报文,append后面就添加你想要返回的报文,返回的数据可以结合你后面处理逻辑的业务层
	       StringBuffer resultBuffer = new StringBuffer();
	       resultBuffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
	       resultBuffer.append("<report_data>");

	       resultBuffer.append("<respon_req>953947334</respon_req>");
	       resultBuffer.append("<respon_time>20120402113943</respon_time>");
	       resultBuffer.append("<result>");
	       resultBuffer.append("<speciality>线路</speciality>");
	       resultBuffer.append("<personnel>王加和</personnel>");
	       resultBuffer.append("<begin_time>20120301000000</begin_time>");
	       resultBuffer.append("<end_time>20120331235959</end_time>");
	       resultBuffer.append("<plan_quantity>50</plan_quantity>");
	       resultBuffer.append("<checkout_quantity>40</checkout_quantity>");
	       resultBuffer.append("<patrol_rate>0.80</patrol_rate>");
	       resultBuffer.append("</item>");
	       resultBuffer.append("</items>");
	       resultBuffer.append("</report_data>");

	 
	       // 设置发送报文的格式
	       response.setContentType("text/xml");
	       response.setCharacterEncoding("UTF-8");
	 
	       PrintWriter out = response.getWriter();
	       out.println(resultBuffer.toString());
	       out.flush();
	       out.close();
	    }
	 
	    protected void doPost(HttpServletRequest request,
	           HttpServletResponse response) throws ServletException, IOException {
	         //将get方法放入post中,为安全性
	    	doGet(request,response);
	    }

}

配置web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app id="WebApp_1531107906806">
  <display-name>Archetype Created Web Application</display-name>
  <!--设置的接口就为 IP:port+项目名+下方定义/SetInfo: http://localhost:8080/myServers/SetInfo -->
  <servlet>
  	<servlet-name>third</servlet-name>
  	<servlet-class>mytest.server.SetInfo</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>third</servlet-name>
  	<url-pattern>/SetInfo</url-pattern>
  </servlet-mapping>
  
</web-app>

之后就是服务的调用,先说说使用java自带的HttpURLConnection,这里不需要导入什么jar包,直接写个类调用就好。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author cwc
 * @date 2018年7月7日  
 * @version 1.0.0 
 * @description: 调用http接口
 */
public class GetConsumer {

	public static void main(String[]args) throws Exception{
		System.out.println("开始发送接收——————————————————————————");
//		tOne();
		String url ="http://localhost:8080/myServers/SetInfo";
		getURLContent(url);
	}
	
	public static void tOne() throws Exception{
		System.out.println("调用servlet开始=================");
	    StringBuffer sendStr = new StringBuffer();
	    sendStr.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
	    sendStr.append("<report_data>");
	    sendStr.append("<request_req>953943547334</request_req>");
	    sendStr.append("<request_time>2012040211394324</request_time>");
	    sendStr.append("<request_param>");
	    sendStr.append("<query_month>201203</query_month>");
	    sendStr.append("</request_param>");
	    sendStr.append("</report_data>");
	    BufferedReader reader = null;
	    try {
	        String strMessage = "";
	        StringBuffer buffer = new StringBuffer();
	        // 接报文的地址
	        URL uploadServlet = new URL(
	               "http://localhost:8080/myServers/SetInfo");
	      
	        HttpURLConnection servletConnection = (HttpURLConnection) uploadServlet
	               .openConnection();
	        // 设置连接参数
	        servletConnection.setRequestMethod("POST");
	        servletConnection.setDoOutput(true);
	        servletConnection.setDoInput(true);
	        servletConnection.setAllowUserInteraction(true);
	        // 开启流,写入XML数据
	        OutputStream output = servletConnection.getOutputStream();
	        System.out.println("发送的报文:");
	        System.out.println(sendStr.toString());
	        output.write(sendStr.toString().getBytes());
	        output.flush();
	        output.close();
	        // 获取返回的数据
	        InputStream inputStream = servletConnection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(inputStream));
	        while ((strMessage = reader.readLine()) != null) {
	           buffer.append(strMessage);
	        }
	        System.out.println("接收返回值:" + buffer);
	    } catch (java.net.ConnectException e) {
	        throw new Exception();
	    } finally {
	        if (reader != null) {
	           reader.close();
	        }
	    }
	} 

	/**
	 * 程序中访问http数据接口
	 */
	public static String getURLContent(String urlStr) {
			/** 网络的url地址 */
			URL url = null;
			/** http连接 */
			HttpURLConnection httpConn = null;
			/**//** 输入流 */
			BufferedReader in = null;
			StringBuffer sb = new StringBuffer();
			try {
				url = new URL(urlStr);
				in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
				String str = null;
				while ((str = in.readLine()) != null) {
					sb.append(str);
				}
			} catch (Exception ex) {
	 
			} finally {
				try {
					if (in != null) {
						in.close();
					}
				} catch (IOException ex) {
				}
			}
			String result = sb.toString();
			System.out.println(result);
			return result;
		}

	    
	    
	    
}

补充:使用httpClient的方式调用


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

/**
 * @author cwc
 * @date 2018年7月10日  
 * @version 1.0.0 
 * @description:通过httpClient调用接口
 */
public class MyHttpClient {

	public static void main(String[]args){

		getHttpData();
		
	}
	public static void getHttpData(){
		 //1.使用默认的配置的httpclient
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = null;
        InputStream inputStream = null;
        CloseableHttpResponse response = null;
        try {
        	 //2.使用get方法,传递参数
        	URI url =new URIBuilder()
					.setScheme("http")
					.setHost("192.168.100.6:8080")//ip:port
					.setPath("/detail/index.htm")//接口
					.setParameter("mkdirName", "/MyTestTwoooooo")//key,value
					.setParameter("fileName", "/MyTestTwo/One")
					.build();
        	System.out.println(url);
        	httpGet = new HttpGet(url);
        	//3.执行请求,获取响应
			response = client.execute(httpGet);
			//看请求是否成功,这儿打印的是http状态码
            System.out.println(response.getStatusLine().getStatusCode());
            //4.获取响应的实体内容,就是我们所要抓取得网页内容
            HttpEntity entity = response.getEntity();
            //5.将其打印到控制台上面
            if (entity != null) {
                inputStream = entity.getContent();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    System.out.println(line);
                }
            }
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
}

方法比较简单,代码可以直接复制使用。

继续加油,最近有些懒了。





posted @ 2018-07-09 16:48  wanchen  阅读(1338)  评论(0编辑  收藏  举报