java 读取外网url问题

起初用httpurl读取外网静态json文件,总是返回状态500,当服务器tomcat重新启动就没有问题了,但是过些时间又不行了, 后来查看浏览器的请求头,用gzip格式压缩后,回来界面发现就没这个问题了, 原因还不知道,但问题总算解决了  

      private static String readhttp_info(String httpUrl) {

    StringBuffer strBuffer = new StringBuffer("");  
            HttpURLConnection httpURLConnection = null;  
            InputStream inputStream = null;  
            BufferedReader rufferedReader = null;  
            //用于解码  
            GZIPInputStream gzin = null;  
              
            try {  
                URL serverUrl = new URL(httpUrl);  
                httpURLConnection = (HttpURLConnection) serverUrl.openConnection();  
                //设置请求的头信息  
                httpURLConnection.setRequestProperty("Accept-charset", "utf-8");  
                httpURLConnection.setRequestProperty("Accept", "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01");  
                httpURLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");  
                httpURLConnection.setRequestProperty("Accept-Language", "zh-CN,en-US;q=0.8,zh;q=0.5,en;q=0.3");  
                httpURLConnection.setRequestProperty("Connection","keep-alive");  
                httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0");  
                System.out.println("请求url的响应状态码:"+httpURLConnection.getResponseCode());  
                //状态码200是请求成功  
                if (HttpURLConnection.HTTP_OK == httpURLConnection.getResponseCode()) {  
                    inputStream = httpURLConnection.getInputStream();  
                    System.out.println("服务器响应的内容的编码格式:"+httpURLConnection.getContentEncoding());  
                    //转码  
                    gzin = new GZIPInputStream(inputStream);  
                    rufferedReader = new BufferedReader(new InputStreamReader(  
                            gzin,"utf-8"));  
                    String str = null;  
                    while ((str = rufferedReader.readLine()) != null) {  
                        strBuffer.append(str);  
                        strBuffer.append("\r\n");  
                    }   
                    System.out.println(strBuffer);  
               }  
            }catch(Exception e) {  
                e.printStackTrace();  
            }finally{  
                httpURLConnection.disconnect();  
                //这里把相关的流也关闭吧,我这里就不写了  
            }  
            
            return strBuffer.toString();
   }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值