Android读取URL的内容(结果后缺少的内容)

时间:2010-01-19 15:23:47

标签: android httpwebrequest

我有以下代码来读取网址的内容

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个字符后缺少内容。有人可以帮我解决这个问题。

注意: 我试图阅读的网址包含一个json响应,所以一切都在一行中我认为这就是为什么我缺少一些内容。

2 个答案:

答案 0 :(得分:10)

试试这个:

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

答案 1 :(得分:3)

这是一个更简洁的版本,用于从Web获取脚本的输出:

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();