Android - 从URL问题中获取数据

时间:2015-02-07 09:06:00

标签: android

我正在尝试从url获取数据,它显示为null。

这是我的代码

                try {
                URL urlA = new URL("http://www.domain.com/work123.html");
                BufferedReader in = new BufferedReader(new InputStreamReader(urlA.openStream()));

                String inputLineA;

                while ((inputLineA = in.readLine()) != null)
                    htmlCodeA += inputLineA;

                in.close();
                } catch (Exception e) {

                    //Log.d(LOG_TAG, "Error: " + e.toString());
                }           

请让我知道我在哪里做错了。

最好的问候,

2 个答案:

答案 0 :(得分:0)

由于您在Android部分发布,因此几乎可以保证您希望在AsyncTask中运行此操作,而不是使用该AsyncTask阻止UIThread。

String htmlCodeA = "";
//
// A bunch of lines later...
try{
  HttpClient client = new DefaultHttpClient();
  HttpPost request = new HttpPost("http://www.domain.com/work123.html");
  HttpResponse response = client.execute(request);
  InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
  BufferedReader reader = new BufferedReader(isr);
  String line = "";
  while((line = reader.readLine())!=null)
  {
    htmlCodeA += line;
  }
}
catch(MalformedURLException e) { /* Do whatever you want here. */}
catch(IOException e) { /* Do whatever you want here. */}

答案 1 :(得分:-1)

URL connectURL = new URL(urlstring);

        HttpURLConnection hc = (HttpURLConnection) connectURL.openConnection();

hc.setConnectTimeout(20 * 1000);

                Enumeration kyes = header.keys();
                while (kyes.hasMoreElements()) {
                    String key = (String) kyes.nextElement();
                    String value = (String) header.get(key);
                    hc.setRequestProperty(key, value);
                }

InputStream is = hc.getInputStream();

                resMessage = new String(readFully(is),  "UTF-8")


public static byte[] readFully(InputStream input) throws IOException
{
    byte[] buffer = new byte[Constants.BUFFER_SIZE];
    int bytesRead;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    while ((bytesRead = input.read(buffer)) != -1)
    {
        output.write(buffer, 0, bytesRead);
    }
    return output.toByteArray();
}