读网上的URL,会出的502错误

 

         最近做一个项目需要调用网络上的资料,是别的公司提供的一个url接口。我们只要拼URL,然后去访问就OK了!

         看起来很简单的调用,却弄了好长时间也算搞定,但是办法也不是很好!

         一开始直接用URLConnection进行读操作。(加上代理)

java 代码
  1.   System.getProperties().put("proxySet","true");   
  2.   System.getProperties().put("proxyHost","IP");   
  3.   System.getProperties().put("proxyPort","PORT");   
  4. URLConnection huc = url.openConnection();      
  5. huc.setDoInput(true);      
  6. StringBuffer str = new StringBuffer();      
  7. BufferedReader in=new BufferedReader(new InputStreamReader(huc.getInputStream()));      
  8. String inputLine;      
  9.  while((inputLine=in.readLine())!=null)      
  10.         str.append(inputLine);      
  11.  in.close();    

           运行发现,验证用户的URL没有问题,但在读用户信息的URL时,却很长时间没有反应,过了大约5分钟左右报502错误

502:是Bad gate way    ,应该是网关错误。开始以为是我们的代理不行。然后就用拨号来试。却发现结果是相同的!

         还以为是URL错误,然后把URL打在浏览器里进行尝试,却发现成功了。

        于是认为是URLConnection这个类的功能不够强大,容错性不行。

        并下httpClient来试,(抱怨一声httpClient的版本太多了,还要code一起运行),终于写好了,尝试运行,

java 代码
  1. StringBuffer str = new StringBuffer();   
  2.             httpclient = new DefaultHttpClient();   
  3.             //httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3,true));   
  4.                
  5.             //代理   
  6.             /**HttpHost targetHost = new HttpHost("serverip",server port, "http");  
  7.             HttpHost proxy = new HttpHost("IP", port);   
  8.             HttpRoute route = new HttpRoute(targetHost, null, proxy, false);  
  9.             HttpGet httpget = new HttpGet("/path");  
  10.             RoutedRequest routedReq = new RoutedRequest.Impl(httpget, route);  
  11.             HttpResponse response = httpclient.execute(routedReq, null);*/  
  12.                
  13.             //不用代理   
  14.             HttpGet httpget = new HttpGet(urlStr);    
  15.             HttpResponse response = httpclient.execute(httpget);   
  16.   
  17.             HttpEntity entity = response.getEntity();   
  18.                
  19.                
  20.                
  21.             if (entity != null) {   
  22.                 BufferedInputStream bis = new BufferedInputStream(entity.getContent());   
  23.                    
  24.                 byte[] b = new byte[1024];   
  25.                 int i=-1;   
  26.                 while((i=bis.read(b))!=-1){   
  27.                     str.append(new String(b,0,i));   
  28.                 }   
  29.             }   
  30.                
  31.                
  32.             if (entity != null) {   
  33.                 entity.consumeContent();   
  34.             }  

          还是不行,同样的问题

 

          于是想是不是这个接口做了控制,(因为浏览器访问从来都是正确结果的),于是想办法封闭请求,便有了下面的代码

java 代码
  1. HttpHost targetHost = new HttpHost("serverip", serverpot, "http");   
  2.    HttpHost proxy = new HttpHost("ip", port);    
  3.    HttpRoute route = new HttpRoute(targetHost, null, proxy, false);   
  4.    HttpGet httpget = new HttpGet("/.......");*/   
  5.    httpget.setHeader("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*");   
  6.    httpget.setHeader("Accept-Language","zh-cn");   
  7.    httpget.setHeader("UA-CPU","x86");   
  8.    httpget.setHeader("Accept-Encoding","gzip,deflate");   
  9.    httpget.setHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");   
  10.    httpget.setHeader("Host","serverip:serverpot");   
  11.    httpget.setHeader("Proxy-Connection""Keep-Alive");   
  12.    RoutedRequest routedReq = new RoutedRequest.Impl(httpget, route);  

          便下载了请求的拦截器,拦截请求,使得它发出的请求和浏览器的相同,可结果令人失望。(要绝望了)

         这时发现,httpclient的重试功能,第二次重试可以成功访问。但中间的时间却有5分钟之久,于是便想减少超时时间

         也许我没找到,或者资料不全,硬是没找到(注:httpcomponents-client-4.0-alpha1-bin,httpcomponents-core-4.0-alpha5-bin用的这两个包来做的)

         于是自己创线程20秒访问不了,就关掉上一个线程,再重试,代码下:

java 代码
  1. public void run(){   
  2.            
  3.         if(isReader){   
  4.             t.cancel();   
  5.         }else{   
  6.                
  7.             /**  
  8.              * 关闭  
  9.              */  
  10.             if(httpclient != null){   
  11.                 httpclient.getConnectionManager().shutdown();   
  12.                 //System.out.println("关闭连接");   
  13.             }   
  14.         }   
  15.     }   
  16.     public void process(){   
  17.            
  18.         try{   
  19.   
  20.             /**  
  21.              * 开始连接  
  22.              */  
  23.             String para = this.getParam(paras);   
  24.             if(para.length()!=0){   
  25.                 urlStr = urlStr + "?" +para;   
  26.             }   
  27.                
  28.             //System.out.println(new Date());   
  29.             //System.out.println(urlStr);   
  30.                
  31.             StringBuffer str = new StringBuffer();   
  32.             httpclient = new DefaultHttpClient();   
  33.             //httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3,true));   
  34.                
  35.             //代理   
  36.             /**HttpHost targetHost = new HttpHost("servertip", serverport, "http");  
  37.             HttpHost proxy = new HttpHost("ip", port);   
  38.             HttpRoute route = new HttpRoute(targetHost, null, proxy, false);  
  39.             HttpGet httpget = new HttpGet("/.......");  
  40.             RoutedRequest routedReq = new RoutedRequest.Impl(httpget, route);  
  41.             HttpResponse response = httpclient.execute(routedReq, null);*/  
  42.                
  43.             //不用代理   
  44.             HttpGet httpget = new HttpGet(urlStr);    
  45.             HttpResponse response = httpclient.execute(httpget);   
  46.   
  47.             HttpEntity entity = response.getEntity();   
  48.                
  49.                
  50.                
  51.             if (entity != null) {   
  52.                 BufferedInputStream bis = new BufferedInputStream(entity.getContent());   
  53.                    
  54.                 byte[] b = new byte[1024];   
  55.                 int i=-1;   
  56.                 while((i=bis.read(b))!=-1){   
  57.                     str.append(new String(b,0,i));   
  58.                 }   
  59.             }   
  60.                
  61.                
  62.             if (entity != null) {   
  63.                 entity.consumeContent();   
  64.             }   
  65.                
  66.             if(str.indexOf("<rawdata></rawdata>")!=-1){   
  67.                     str.delete(str.indexOf("<rawdata></rawdata>"), str.indexOf("")+"".length());   
  68.             }   
  69.             String xmlStr = this.toUnicode(str.toString(), "gb2312");   
  70.             InputStream sbis = new StringBufferInputStream(xmlStr);   
  71.             //System.out.println(xmlStr);   
  72.             //System.out.println(new Date());   
  73.             DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();   
  74.             DocumentBuilder db=dbf.newDocumentBuilder();   
  75.             doc=db.parse(sbis);   
  76.             //is.close();   
  77.             sbis.close();   
  78.             this.isReader = true;   
  79.         }      
  80.         catch(Exception e)      
  81.         {      
  82.             //log.error(e);   
  83.             //e.printStackTrace();     
  84.             process();   
  85.         }      
  86.         finally      
  87.         {      
  88.                
  89.         }   
  90.     }   
  91.     public Document processUrl(String urlStr,Map paras){   
  92.         this.urlStr = urlStr;   
  93.         this.paras = paras;   
  94.            
  95.         t = new Timer();   
  96.         t.schedule(this,50005000);   
  97.            
  98.         //this.run();   
  99.         this.process();   
  100.            
  101.         t.cancel();   
  102. }   
  103. private   String   toUnicode(String   strText,String   code)   throws   UnsupportedEncodingException{        
  104.         char   c;        
  105.           String   strRet   =   ""   ;        
  106.           int   intAsc;        
  107.           String   strHex;        
  108.           strText   =   new   String(strText.getBytes("gb2312"),code);        
  109.           for   (   int   i   =   0;   i   <   strText.length();   i++   ){        
  110.           c   =   strText.charAt(i);        
  111.           intAsc   =   (int)c;        
  112.           if(intAsc>128){        
  113.           strHex   =   Integer.toHexString(intAsc);        
  114.           strRet   =   strRet   +   "&#x"   +   strHex+";";        
  115.           }        
  116.           else{        
  117.           strRet   =   strRet   +   c;        
  118.           }        
  119.           }        
  120.           return   strRet   ;        
  121.       }   

   运行了一下,结果还行,就是这个办法不规范啊!(最后还有编码问题,郁闷死了)。唉!

    还有关于这个问题,我了贴子问问的,可怎么老是被放到入门贴呢,还扣分。呵呵。但问题总算有个说法了!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值