zoukankan      html  css  js  c++  java
  • 远程访问(HttpClient和HttpResponse的使用) 原型模式

      1 package com.webserver.webservice;
      2 
      3 import java.io.ByteArrayInputStream;
      4 import java.io.FileOutputStream;
      5 import java.io.IOException;
      6 import java.net.SocketTimeoutException;
      7 import java.text.SimpleDateFormat;
      8 import java.util.Date;
      9 import java.util.Iterator;
     10 import java.util.Map;
     11 import java.util.Set;
     12 import java.util.concurrent.ConcurrentHashMap;
     13 
     14 import javax.servlet.ServletException;
     15 import javax.servlet.annotation.WebServlet;
     16 import javax.servlet.http.HttpServlet;
     17 import javax.servlet.http.HttpServletRequest;
     18 import javax.servlet.http.HttpServletResponse;
     19 
     20 import org.apache.http.Header;
     21 import org.apache.http.HttpResponse;
     22 import org.apache.http.client.ClientProtocolException;
     23 import org.apache.http.client.HttpClient;
     24 import org.apache.http.client.methods.HttpPost;
     25 import org.apache.http.entity.BasicHttpEntity;
     26 import org.apache.http.impl.client.DefaultHttpClient;
     27 import org.apache.http.params.CoreConnectionPNames;
     28 import org.apache.http.util.EntityUtils;
     29 
     30 /**
     31  * Servlet implementation class Prompt
     32  */
     33 @WebServlet("/Prompt")
     34 public class Prompt extends HttpServlet {
     35     private static final long serialVersionUID = 1L;
     36     private static Map<String, CookieData> cookieMap  = new ConcurrentHashMap<String,CookieData>();
     37     public static String yuyinServer = "http://10.3.172.205:8080/RecognizePY/directRecognize"; 
     38     /**
     39      * @see HttpServlet#HttpServlet()
     40      */
     41     public Prompt() {
     42         super();
     43         // TODO Auto-generated constructor stub
     44     }
     45 
     46     /**
     47      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     48      */
     49     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     50         // TODO Auto-generated method stub
     51         this.doPost(request, response);
     52     }
     53 
     54     /**
     55      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     56      */
     57     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     58         String session = request.getParameter("session").trim();
     59         //String token = request.getParameter("token").trim();
     60         response.setCharacterEncoding("UTF-8");
     61         response.setContentType("text/json;charset=utf-8");
     62         String firstCookie = "";
     63         //从原型管理器中获取原型对象
     64         CookieData cookie = cookieMap.get(session);
     65         //原型管理器包含该对象
     66         if(cookie!=null){
     67             firstCookie = cookie.getCookie();
     68             cookie.setAccessDate(System.currentTimeMillis());
     69         } else {
     70             //不包含就创建一个对象 并存到原型管理器中
     71             CookieData tmpCookie = new CookieData();
     72             firstCookie = getCookie();
     73             tmpCookie.setCookie(firstCookie);
     74             tmpCookie.setAccessDate(System.currentTimeMillis());
     75             cookieMap.put(session, tmpCookie);
     76             //根据具体情况 原型对象在原型管理器中存放时间超过规定时间移除改原型对象
     77             cleanCookieMap();
     78         }
     79         //TODO
     80         //....
     81         
     82     }
     83     
     84     
     85     /**
     86      * 客户端要记住返回的cookie
     87      * @return
     88      * @throws ClientProtocolException
     89      * @throws IOException
     90      */
     91     public String getCookie() throws ClientProtocolException, IOException{
     92         String firstCookie = "";
     93         try{
     94             HttpClient client = new DefaultHttpClient();
     95             HttpPost post = new HttpPost(yuyinServer);
     96             //设置连接超时时间
     97             client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
     98             //设置数据传输超时时间
     99             client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);
    100             HttpResponse response = null;
    101             response = client.execute(post);
    102             if(response.getStatusLine().getStatusCode()==200){
    103                 //如果状态码为200,就是正常返回 
    104                 Header[] cookies = response.getHeaders("Set-Cookie");
    105                 for( int i=0;i<cookies.length;i++){
    106                     Header curr = cookies[i];
    107                     firstCookie += curr.getValue();
    108                 }
    109             }
    110         }catch(SocketTimeoutException e){
    111             firstCookie = null;
    112         }
    113         return firstCookie;
    114     }
    115 
    116     /**
    117      * 送语音数据,拿到识别结果
    118      * @param out
    119      * @return
    120      * @throws IOException 
    121      * @throws ClientProtocolException 
    122      */
    123     public String getReconizedResult(byte[] wavbt,String cookie) throws ClientProtocolException, IOException{
    124         String retStr = "";
    125         try {
    126             HttpClient client = new DefaultHttpClient();
    127             client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
    128             client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);
    129             HttpPost post = new HttpPost(yuyinServer);
    130             post.addHeader("Cookie",cookie);
    131             //以流的方式传参数(有两种方式)
    132             //第一中方式
    133             //InputStreamEntity entity  = new InputStreamEntity(new ByteArrayInputStream(wavbt), wavbt.length);
    134             //第二种方式
    135             BasicHttpEntity entity = new BasicHttpEntity();  
    136             //设置内容  
    137             entity.setContent(new ByteArrayInputStream(wavbt)); 
    138             //设置长度  
    139             entity.setContentLength(wavbt.length);  
    140             post.setEntity(entity);
    141             HttpResponse response= null;
    142             response = client.execute(post);
    143             String respStr = EntityUtils.toString(response.getEntity());
    144             org.json.JSONObject retJsonObj = new org.json.JSONObject(respStr);
    145             retStr = retJsonObj.getString("result");
    146             saveFile("success",wavbt);
    147         } catch (Exception e) {
    148             System.out.println(e.getMessage());
    149             saveFile("fail",wavbt);
    150         }
    151         
    152         return retStr; 
    153     }
    154 
    155     public static void saveFile(String flag,byte[] wavbt) {
    156         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    157         try (
    158             FileOutputStream fos = new FileOutputStream("d:/test"+flag+ df.format(new Date()) +".wav");
    159         ) {
    160             fos.write(wavbt);
    161         } catch (Exception e) {
    162             
    163         }
    164     }
    165     
    166     //自定义的原型对象
    167     class CookieData{
    168         /** 访问cookie */
    169         private String cookie;
    170     
    171         /** 访问时间 */
    172         private long accessDate;
    173 
    174         /**
    175          * 返回 cookie
    176          * @return cookie
    177          */
    178         public String getCookie() {
    179             return cookie;
    180         }
    181 
    182         /**
    183          * 设置 cookie
    184          * @param cookie
    185          */
    186         public void setCookie(String cookie) {
    187             this.cookie = cookie;
    188         }
    189 
    190         /**
    191          * 返回 accessDate
    192          * @return accessDate
    193          */
    194         public long getAccessDate() {
    195             return accessDate;
    196         }
    197 
    198         /**
    199          * 设置 accessDate
    200          * @param accessDate
    201          */
    202         public void setAccessDate(long accessDate) {
    203             this.accessDate = accessDate;
    204         }
    205     }
    206     
    207     //存放时间超过规定时间后清除原型对象
    208     public void cleanCookieMap(){
    209         long currTime = System.currentTimeMillis();
    210         Set<String> keySet = cookieMap.keySet();
    211         Iterator<String> it = keySet.iterator();
    212         while(it.hasNext()){
    213             String key = it.next();
    214             CookieData cookie = cookieMap.get(key);
    215             //如果cookie保存时间超过一小时 则移除
    216             if(currTime - cookie.getAccessDate()> 3600000 ){
    217                 cookieMap.remove(key);
    218             }
    219         }
    220     }
    221 }
  • 相关阅读:
    分布式版本控制系统Git的安装与使用
    随笔--第一篇博客
    字符串、文件操作,英文词频统计预处理
    了解大数据的特点、来源与数据呈现方式
    第五次作业-结对项目四则运算 “软件”之升级版
    第四次作业:个人项目-小学四则运算 “软件”之初版
    读《构建之法》1-5章有感
    第二次作业——分布式版本控制系统Git的安装与使用
    第一次作业——感想
    【大数据】字符串、文件操作,英文词频统计预处理
  • 原文地址:https://www.cnblogs.com/Wen-yu-jing/p/3861159.html
Copyright © 2011-2022 走看看