Android阅读一个URL的内容(结果中缺less的内容)

我有下面的代码读取一个url的内容

public static String DownloadText(String url){ StringBuffer result = new StringBuffer(); try{ URL jsonUrl = new URL(url); InputStreamReader isr = new InputStreamReader(jsonUrl.openStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while ((inputLine = in.readLine()) != null){ result.append(inputLine); } }catch(Exception ex){ result = new StringBuffer("TIMEOUT"); Log.e(Util.AppName, ex.toString()); } in.close(); isr.close(); return result.toString(); } 

问题是我在返回的结果中有4065个字符后缺less内容。 有人可以帮我解决这个问题。

注:我试图读取的url包含一个JSON响应,所以一切都在一行我想这就是为什么我有一些内容丢失。

Solutions Collecting From Web of "Android阅读一个URL的内容(结果中缺less的内容)"

尝试这个:

 try { feedUrl = new URL(url).openConnection(); } catch (MalformedURLException e) { Log.v("ERROR","MALFORMED URL EXCEPTION"); } catch (IOException e) { e.printStackTrace(); } try { in = feedUrl.getInputStream(); json = convertStreamToString(in); }catch(Exception e){} 

而convertStreamToString是:

 private static String convertStreamToString(InputStream is) throws UnsupportedEncodingException { BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8")); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } 

这里是一个更清洁的版本来获取从networking脚本的输出:

 public String getOnline(String urlString) { URLConnection feedUrl; try { feedUrl = new URL(urlString).openConnection(); InputStream is = feedUrl.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8")); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + ""); } is.close(); return sb.toString(); }catch(Exception e){ e.printStackTrace(); } return null; } 

请记住,你不能从主线程下载任何东西。 它必须来自一个单独的线程。 使用类似于:

 new Thread(new Runnable(){ public void run(){ if(!isNetworkAvailable()){ Toast.makeText(getApplicationContext(), getResources().getString(R.string.nointernet), Toast.LENGTH_LONG).show(); return; } String str=getOnline("http://www.example.com/script.php"); } }).start();