【问题标题】:HttpGet not recognizing urlHttpGet无法识别网址
【发布时间】:2011-04-22 18:49:28
【问题描述】:

所以我使用的是另一篇较早的帖子中的以下代码,但有一部分有问题,HttpGet request = new HttpGet(url); 行不起作用。在 url 位置我放了类似www.stackoverflow.com 的东西,但那一部分不会让代码编译。我基本上是在尝试从 html 网站中提取文本。完整代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(www.stackoverflow.com);
    HttpResponse response = client.execute(request);

    String html = "Toronto-GTA";
    InputStream in = response.getEntity().getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder str = new StringBuilder();
    String line = null;
    while((line = reader.readLine()) != null)
    {
        str.append(line);
    }
    in.close();
    html = str.toString();
}

【问题讨论】:

  • 对于 HttpGet 请求 = new HttpGet(www.stackoverflow.com);我将其更改为(“www.stackoverflow.com”);正如许多人所建议的那样,但其他行如“HttpResponse response = client.execute(request);”返回编译错误,都是:未处理的异常类型IOException,eclipse中的大部分快速修复建议“Surroned with try/catch”

标签: java android html syntax apache-commons-httpclient


【解决方案1】:

HTTPGet 需要 URL 或字符串,因此请尝试将您的请求行更改为:

HttpGet request = new HttpGet("http://www.stackoverflow.com/");

【讨论】:

    【解决方案2】:

    使用形式的字符串:

    [scheme:][//authority][path][?query][#fragment]
    

    "http://www.stackoverflow.com"

    【讨论】:

      【解决方案3】:

      试试这个:HttpGet request = new HttpGet("www.stackoverflow.com");

      【讨论】:

      • 我尝试更改它,使 url 有“”,但这会导致如下行:“HttpResponse response = client.execute(request);”、“InputStream in = response.getEntity().getContent( );",以及更多错误。
      • “错误输出”是指编译错误还是运行时异常?如果是例外,请发布。
      • 编译错误,都是:未处理的异常类型IOException,eclipse中大部分快速修复提示“Surroned with try/catch”
      【解决方案4】:

      除了上面给出的答案之外,您还可以用 try 和 catch 语句来捕获异常。

      try{
      HttpClient client = new DefaultHttpClient();
          HttpGet request = new HttpGet("www.stackoverflow.com");
          HttpResponse response = client.execute(request);
          InputStream in = response.getEntity().getContent();
          BufferedReader reader = new BufferedReader(new InputStreamReader(in));
          StringBuilder str = new StringBuilder();
          String line, html = null;
          while((line = reader.readLine()) != null)
          {
              str.append(line);
          }
          in.close();
          html = str.toString();
      }
      catch(Exception e){
      //Do something here like printing the stacktrace
      }
      

      【讨论】:

        猜你喜欢
        • 2019-09-14
        • 2011-10-16
        • 2016-07-03
        • 1970-01-01
        • 2012-11-25
        • 2015-04-23
        • 1970-01-01
        • 1970-01-01
        • 2016-05-25
        相关资源
        最近更新 更多