【问题标题】:Flutter fetch a webpage with user-agent parameterFlutter 使用用户代理参数获取网页
【发布时间】:2019-07-22 07:36:43
【问题描述】:

我正在使用 Flutter http 包来获取网页。 我想发送像桌面这样的http请求。我该怎么做?

我的用户代理:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"

我的代码;

  String text="mert";
  var isLoading = false;



 _fetchData() async {


final response =
    await http.get("http://trscript.net");
if (response.statusCode == 200) {

 var document = parse(response.body.toString());
 if(document.querySelector("body > div > div.sol.yaklas > div:nth-child(1) > article > div.yazi_bilgi")!=null){
    text = document.querySelector("body > div > div.sol.yaklas > div:nth-child(1) > article > div.yazi_bilgi").text;
 }

} else {
  throw Exception('Failed to load photos');
}

}

【问题讨论】:

    标签: http flutter dart httprequest


    【解决方案1】:

    您需要创建自定义http.Client,覆盖它的send 方法并使用它来发送请求。
    示例代码:

    import 'package:http/http.dart' as http;
    
    class ClientWithUserAgent extends http.Client {
    
      final http.Client _client;
    
      ClientWithUserAgent(this._client);
    
      @override
      Future<http.StreamedResponse> send(http.BaseRequest request) async {
        request.headers['User-Agent'] = 'user agent value';
        return _client.send(request);
      }
    
    }
    

    然后你就可以这样使用它了:

    final client = ClientWithUserAgent(http.Client());
    
    final response = await client.get('some_url');
    

    另请注意,将原始 http.Client 传递给构造函数允许使用各种客户端修改的组合,如标题、日志记录等。
    如果你不需要它,你可以在ClientWithUserAgent 中实例化http.Client()

    【讨论】:

    • 因为 http: ^0.12.2 你应该从 BaseClient 扩展。
    【解决方案2】:

    基于http 包最新版本documentation 你应该扩展http.BaseClient。 直接从文档中复制的代码:

    lass UserAgentClient extends http.BaseClient {
      final String userAgent;
      final http.Client _inner;
    
      UserAgentClient(this.userAgent, this._inner);
    
      Future<http.StreamedResponse> send(http.BaseRequest request) {
        request.headers['user-agent'] = userAgent;
        return _inner.send(request);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-10
      相关资源
      最近更新 更多