起初用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(); }