ls请求代码

import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer;

import com.lingtu.starmap2.util.GetResource;

import org.apache.log4j.Logger; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder;

import com.lingtu.starmap2.mapsearch.model.LsItemModel; import com.lingtu.starmap2.mapsearch.model.MapSearchModel; import com.lingtu.starmap2.mapsearch.model.ResultInfoModel; import com.lingtu.starmap2.util.WebUtil;

/**  * 处理客户端搜索请求类。提供两个createRequest()方法,分别用于创建矩形查询和关键字查询的SearchRequest的实  * 例,创建完毕后调用execute()进行实际的查询操作。  */ public class SearchLsRequest {

    static Logger logger = Logger.getLogger(SearchLsRequest.class.getName());

  

    /**      * 默认构造器      *      */

    /**      * 创建包含关键字查询时需要信息的SearchRequest实例,该方法时一个静态(static)方法。      *      * @param geoType 查询的地物类型      * @param scope 查询的区域范围,可以选择的项有MapSearcher.SCOPE_PROVINCE、MapSearcher.SCOPE_CITY      *            、MapSearcher.SCOPE_CURRENT_SCREEN,如果参数的值不属于以上范围,则默认使用MapSea      *            rcher.SCOPE_CURRENT_SCREEN并将相关信息记录日志。      * @param matchType 关键字的匹配类型,可以选择的值为MapSearcher.FULL_MATCH、MapSearcher.PATIAL_MATCH      *            ,如果参数的值不在以上范围,则默认使用MapSearcher.PATIAL_MATCH并将相关信息记录日 志。      * @param geoValue 查询地物的关键字      * @param resultCount 限制查询的总数      * @param page 查询第几页的数据      * @param prePageCount 每页显示的数据条数      *                  * @return SearchRequest 查询地物对象      */

    /**      * 属性设置完毕后,调用该方法进行实际的查询操作,返回值为Item类的实例组成的集合。      *      * @return ArrayList 查询的结果集。      */     public ResultInfoModel execute(String city,int lat,int lng,String words ) {         String result = null;         //if (msModel.getSearchType() == MapSearchModel.RECT_SEARCH) {         //    result = generateRectRequest();         //} else if (msModel.getSearchType() == MapSearchModel.WORD_SEARCH) {             result = generatePointRequest( city, lat, lng, words);         //} if (msModel.getSearchType() == MapSearchModel.POINT_SEARCH) {         //    result = generatePointRequest();         //}                 String response = search(result);                 return parseResponse(response);     }

    /**      * 根据提供的信息生成XML格式的请求      *      * @return String XML格式的请求      */     private String generateRectRequest() {         /*         Element wms = new Element("WMS");         wms.setAttribute("method", "request").setAttribute("function", "search");         Document doc = new Document(wms);                 Element feature = new Element("Feature");         feature.addContent(new Element("name").addContent("search"));         feature.addContent(new Element("version").addContent("1.0"));         feature.addContent(new Element("description"));         wms.addContent(feature);                 Element search = new Element("Search");         Element searchFeature = new Element("Feature");         search.addContent(searchFeature);*/                 StringBuffer strBuffer = new StringBuffer("");         strBuffer.append("LocalSearch&city=北京&area=CIRCLE(11632624 3999561,100)&words=清华大学");

        //System.out.println(strBuffer);         return strBuffer.toString();     }         /**      * 根据提供的信息生成XML格式的请求      *      * @return String XML格式的请求      */     private String generateWordRequest(String city,int lat,int lng,String words) {      /**       * 空间几何搜索  LocalSearch&city=北京&area=POINT(11632624 3999561)&words=清华大学  LocalSearch&city=北京&area=CIRCLE(11632624 3999561,100)&words=清华大学  LocalSearch&city=北京&area=RECT(11632624 3999561,11668624 3997561)&words=清华大学

      */         StringBuffer strWordBuffer = new StringBuffer("");                 strWordBuffer.append("LocalSearch&city="+city+"&area=RECT("+lat+" "+lng+","+lat+" "+lng+")&words="+words);             return strWordBuffer.toString();     }         /**      * 根据提供的信息生成XML格式的请求      *      * @return String XML格式的请求      */     private String generatePointRequest(String city,int lat,int lng,String words) {         StringBuffer strBuffer = new StringBuffer("");         strBuffer.append("LocalSearch&city=北京&area=CIRCLE(11632624 3999561,100)&words=清华大学");    

        //System.out.println(strBuffer);         return strBuffer.toString();     }     /**      * 搜索地物。      * @param xmlRequest XML格式的请求。      * @return XML格式的响应信息。      */     private String search(String xmlRequest) {         // TODO         URL url = null;         StringBuffer strBuffer = new StringBuffer("");         PrintWriter writer = null;         BufferedReader in = null;            try {          //String test="http://ls.vip.51ditu.com/";          String test="http://ls.vip.51ditu.com/LocalSearch?LocalSearch&city=北京&area=POINT(11632624%203999561)&words=清华大学";                    url=new URL(test);             //url = new URL(GetResource.getXMLValue("mapsearchlsurl"));             URLConnection conn = url.openConnection();             conn.setDoInput(true);             conn.setDoOutput(true);            

                        //writer = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));             //writer.write("LocalSearch?"+xmlRequest);             //writer.flush();             //conn.connect();             in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));             String line = null;             while ((line = in.readLine()) != null) {                 strBuffer.append(line + "/n");             }         } catch ( MalformedURLException e) {             logger.error("获得到smartls的连接时发生异常");         } catch (IOException e) {             logger.error("从smartls中获得搜索结果时发生IO异常", e);         } finally {                         try {              if (writer != null) writer.close();                 if (in != null) in.close();             } catch (IOException e) {}         }         return strBuffer.toString();     }         /**      * 被search()方法使用,用于将XML格式的查询响应信息分解ResultInfo类的实例。      *      * @param xmlResponse XML格式的查询响应信息      *      *      *   <?xml version="1.0" encoding="GBK" ?> - <Result time="0" error="0"> - <PoiRes total="249"> - <Poi id="1">   <LSID v="11/215/3151035607" />   <Na v="清华大学" />   <Geo lo="11632641" la="4000193" />   <LSIDE v="11/215/3151035607" />   <LSIDN v="11/215/3151035607" />   <Dis v="702" />   <Ext v="3151035607_i.jpg,3151035607.jpg" />   </Poi>   </PoiRes>   </Result>      *      * @return 查询结果      */     private ResultInfoModel parseResponse(String xmlResponse) {         List results = new ArrayList();         SAXBuilder builder = new SAXBuilder();         Document document = null;         try {             document = builder.build(new StringReader(xmlResponse));         } catch (JDOMException e) {             logger.error("解析响应信息时发生XML解析异常", e);         }                 Element rootElement = document.getRootElement();         ResultInfoModel resultInfo = new ResultInfoModel();         Element result = rootElement.getChild("Result");         int total = WebUtil.parseInt(result.getChildText("total"), 0);         resultInfo.setTotal(total);         //int currentPage = WebUtil.parseInt(result.getChildText("currentPage"), 0);         //resultInfo.setCurrentPage(currentPage);         //int count = WebUtil.parseInt(result.getChild("POIList").getAttributeValue("count"), 0);         //resultInfo.setCount(count);         Element itemList = result.getChild("PoiRes");         List list = itemList.getChildren();         for (int i = 0; i < list.size(); i++) {             LsItemModel item = new LsItemModel();             Element e = (Element) list.get(i);             item.setId(e.getChildText("id"));             item.setLSID(e.getChildText("LSID"));             item.setNa(e.getChildText("Na"));             item.setLo(e.getChildText("lo"));             item.setLa(e.getChildText("la"));             item.setLSIDE(e.getChildText("LSIDE"));             item.setLSIDN(e.getChildText("LSIDN"));                         results.add(item);         }         resultInfo.addResults(results);         return resultInfo;     }         public static String sendGet(String url,String param) {         String result = "";         BufferedReader in=null;         StringBuffer strBuffer = new StringBuffer("");         try{              String urlName = url + "?"+param;              URL U = new URL(urlName);              URLConnection connection = U.openConnection();

             connection.connect();    //BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));              in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));              String line = null;      while ((line = in.readLine()) != null) {        strBuffer.append(line + "/n");      }       in.close();       }catch(Exception e){       System.out.println("没有结果!"+e);      }      return result;    }         public static String sendPost(String url,String param){        String result=""; //       try{ //        URL httpurl = new URL(url); //        HttpURLConnection httpConn = (HttpURLConnection)httpurl.openConnection();      //        httpConn.setDoOutput(true); //        httpConn.setDoInput(true); //        PrintWriter out = new PrintWriter(httpConn.getOutputStream()); //        out.print(param); //        out.flush(); //        out.close(); //        BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); //        String line; //        while ((line = in.readLine())!= null) //        { //         result += line; //        } //        in.close(); //       }catch(Exception e){ //        System.out.println("没有结果!"+e); //       } //       return result;      try{      HttpURLConnection urlConn=(HttpURLConnection)(new URL(url).openConnection());      //urlConn.addRequestProperty("Cookie",cookie);      urlConn.setRequestMethod("POST");      urlConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");      //urlConn.setFollowRedirects(true);      urlConn.setDoOutput(true); // 需要向服务器写数据      urlConn.setDoInput(true); //      urlConn.setUseCaches(false); // 获得服务器最新的信息      urlConn.setAllowUserInteraction(false);      urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");      urlConn.setRequestProperty("Content-Language","en-US" );      urlConn.setRequestProperty("Content-Length", ""+param.length());

     DataOutputStream outStream = new DataOutputStream(urlConn.getOutputStream());      outStream.writeBytes(param);      outStream.flush();      outStream.close();

     //cookie=urlConn.getHeaderField("Set-Cookie");      //BufferedReader br=new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"gb2312"));      BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));      String line;      while ((line = in.readLine())!= null)      {       result += line;      }      in.close();     }catch(Exception e){      System.out.println("没有结果!"+e);     }     return result;                  }

    public static void DownLoadPages1(String urlStr, String outPath)     {         int chByte = 0;         URL url = null;         HttpURLConnection httpConn = null;         InputStream in = null;         FileOutputStream out = null;

        try         {             url = new URL(urlStr);             httpConn = (HttpURLConnection) url.openConnection();             HttpURLConnection.setFollowRedirects(true);             httpConn.setRequestMethod("GET");             httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");                         // logger.info(httpConn.getResponseMessage());             in = httpConn.getInputStream();             out = new FileOutputStream(new File(outPath));

            chByte = in.read();             while (chByte != -1)             {                 out.write(chByte);                 chByte = in.read();             }         }         catch (MalformedURLException e)         {             e.printStackTrace();         }         catch (IOException e)         {             e.printStackTrace();         }         finally         {             try             {                 out.close();                 in.close();                 httpConn.disconnect();             }             catch (Exception ex)             {                 ex.printStackTrace();             }         }     }

            public static void DownLoadPages(String urlStr, String outPath)     {         int chByte = 0;         URL url = null;         HttpURLConnection httpConn = null;         InputStream in = null;         FileOutputStream out = null;

        try         {             url = new URL(urlStr);             httpConn = (HttpURLConnection) url.openConnection();             HttpURLConnection.setFollowRedirects(true);             httpConn.setRequestMethod("GET");             httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");                         // logger.info(httpConn.getResponseMessage());             in = httpConn.getInputStream();             out = new FileOutputStream(new File(outPath));

            chByte = in.read();             while (chByte != -1)             {                 out.write(chByte);                 chByte = in.read();             }         }         catch (MalformedURLException e)         {             e.printStackTrace();         }         catch (IOException e)         {             e.printStackTrace();         }         finally         {             try             {                 out.close();                 in.close();                 httpConn.disconnect();             }             catch (Exception ex)             {                 ex.printStackTrace();             }         }     }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值