0

以前我创建了一个 REST API,它从颤振移动应用程序获取一个 ZIP 文件和两个其他参数作为输入

var uri = Uri.parse("http://XX.XXX.XX.XX/gatewayapp/userinfo/sendFileToServer/");
var request = http.MultipartRequest('POST', uri);
     Map<String, String> headers = {
       "Accept": "application/json"
     };
     //add headers
     request.headers.addAll(headers);
     request.fields["customerNumber"] = customerNumber;
     request.fields['zippassword'] = password;
   var file=  await http.MultipartFile.fromPath(
         'userDetailsFile',
         filePath
     );
     request.files.add(file);
     
     await request.send().then((streamedResponse) async {
     ....Implemented the business logic on the response which I was getting
     }

它按预期工作。

我们使用 AWS 服务器上的 Nginx 将 API 从HTTP 移动到 HTTPS,并使用 HTTPClient 和 HttpClientRequest 更改了移动应用程序的所有 GET 和 POST 调用,它按预期工作。

但是,我们无法在 API 上使用 HTTPClient 和 HttpClientRequest 进行多部分请求。我尝试使用 httpclient 方法,但没有运气。我还尝试了以下链接中给出的内容:

在 Dart lang github 上使用 HTTPClient

var uri = Uri.parse("https://XX.XXX.XX.XX/gatewayapp/userinfo/sendFileToServer/");    
HttpClient client = await CommonController.createHttpClient();
HttpClientRequest request = await client.post( uri.toString() , 443, filePath);

谁能帮助我朝着正确的方向前进?任何帮助,将不胜感激!谢谢

4

1 回答 1

0

很抱歉这么晚才回答这个问题。

我能够使用 Flutter 提供的 HTTPClient使用 SSL(部署在 AWS 上的自签名证书)发送 ZIP 文件。

问题

  1. 当我们使用 Open SSL 生成证书并将这些证书添加到 NGINX 配置中以启用 SSL 时。(它没有root权限。)

  2. HTTPClientRequest通过在下面的代码中添加 SSL 证书,我们能够命中第一个 HTTPS 请求。但在随后的 HTTP 请求中出现错误。

    static Future createHttpClient(//Passing the parameters) async { 
        SecurityContext securityContext = SecurityContext.defaultContext;
        var certificate = (await 
        rootBundle.load(Constants.HTTPS_CRT_PATH)).buffer.asInt8List();
        var key = (await rootBundle.load(Constants.HTTPS_KEY_PATH)).buffer.asInt8List();
        securityContext.useCertificateChainBytes(certificate);
        securityContext.usePrivateKeyBytes(key);
        HttpClient httpClient = new HttpClient(context: securityContext);
        httpClient.badCertificateCallback =
            ((X509Certificate cert, String host, int port) => true);
        HttpClientRequest request = httpClient.postUrl(Uri.parse(url));
        request.contentLength = json.encode(requestBody).length;
        request.write(json.encode(requestBody));
        HttpClientResponse response = await request.close();
        print("response status code "+response.statusCode.toString());
        return response;
    }
    
  3. 每次我们发出 HTTP 请求并收到 Bad SSL Handshake 异常错误时,我们都会添加证书:

    I/flutter ( 9066): HandshakeException: Handshake error in client (OS Error:
    I/flutter ( 9066): CERTIFICATE_VERIFY_FAILED: self signed certificate(handshake.cc:354)) 
    

解决问题的步骤

  1. 将证书添加到/etc/ssl/系统文件夹中,因为证书需要 root 访问权限。
  2. 其次,我们需要在发出第一个 HTTP 请求时使用单例设计模式添加一次证书。
  3. 第三,在进行任何 HTTP 调用时,我们只需要使用 HTTP Client 的 Multipart 方法来发送请求。

我将添加代码示例以使用单例模式添加证书并进行 HTTP 调用。

于 2020-09-19T15:22:50.633 回答