URL在浏览器中打开,但不在android程序中打开

时间:2013-05-25 15:36:12

标签: android httpclient

在PC和移动浏览器(chrome)上有一个可以正常打开的URL,但是当我尝试使用下面的代码在Android程序中打开它时会出现以下错误。

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
  String response = "";
  for (String url : urls) {
    //DefaultHttpClient client = new DefaultHttpClient();
      HttpClient client = AndroidHttpClient.newInstance("Android");
    HttpGet httpGet = new HttpGet(url);
   // httpGet.setHeader("User-Agent", "Chrome");
    try {
      HttpResponse execute = client.execute(httpGet);
      InputStream content = execute.getEntity().getContent();

      BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
      String s = "";
      while ((s = buffer.readLine()) != null) {
        response += s;
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  return response;
}

运行代码我从服务器收到Access Denied错误。如果我尝试任何其他网址,它工作正常。我已经尝试搜索如何设置用户代理以绕过服务器上的任何限制,但无法成功。请帮忙。

此外,我已经看到调用此网址的网页的标题部分(来自浏览器)包含以下内容

 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
 <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
 <meta name="apple-mobile-web-app-capable" content="yes" />
 <meta name="HandheldFriendly" content="true" />
 <meta name="MobileOptimized" content="width" />
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

1 个答案:

答案 0 :(得分:1)

我创建了一个php文件,如下所示

<?php
$headers = apache_request_headers();

foreach ($headers as $header => $value) {
echo "$header: $value <br />\n";
}
?>

我从PC浏览器和Android代码中调用了此页面。使用httpGet.setHeader(名称,值)添加了Android代码中来自PC浏览器的所有标头值

现在正在运作。 :)