首页 > 解决方案 > Http 响应:无法将 JSON 转换为流

问题描述

我在 JAVA 中有一个 API,可以将 zip 文件上传到 Delphi 中的服务器,我这样做如下:

        DSRESTConnection conn = new DSRESTConnection();
        conn.setHost("example.com");
        conn.setPort(8080);
        TServerMethods1 proxy = new TServerMethods1(conn);
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(baos);
            ZipOutputStream zos = new ZipOutputStream(bos);
            zos.putNextEntry(new ZipEntry("test.json"));
            byte[] bytes = inputJson.getBytes();
            zos.write(bytes, 0, bytes.length);
            zos.close();
            bos.close();
            baos.close();
            TStream outZip = new TStream(baos.toByteArray());

            zipResponse = proxy.UserZipUpLoad("username", "password", 5, outZip, outZip.asByteArray().length);
        } catch (DBXException | IOException e) {
            e.printStackTrace();
        }

这是API:

    public UserZipUpLoadReturns UserZipUpLoad(String user, String pwd, int ZipType, TStream strmUpLoad, long iSize) throws DBXException {
  DSRESTCommand cmd = getConnection().CreateCommand();
  cmd.setRequestType(DSHTTPRequestType.POST);
  cmd.setText("TServerMethods1.UserZipUpLoad");
  cmd.prepare(get_TServerMethods1_UserZipUpLoad_Metadata());
  cmd.getParameter(0).getValue().SetAsString(user);
  cmd.getParameter(1).getValue().SetAsString(pwd);
  cmd.getParameter(2).getValue().SetAsInt32(ZipType);
  cmd.getParameter(3).getValue().SetAsStream(strmUpLoad);
  cmd.getParameter(4).getValue().SetAsInt64(iSize);
  getConnection().execute(cmd);
  UserZipUpLoadReturns ret = new UserZipUpLoadReturns();
  ret.ReturnCode = cmd.getParameter(5).getValue().GetAsInt32();
  ret.ReturnString = cmd.getParameter(6).getValue().GetAsString();
  ret.returnValue = cmd.getParameter(7).getValue().GetAsInt32();
  return ret;
}

为了创建请求的主体,_parameter 由 API 中的参数创建,这些参数不能在 url 中,例如 byteArray 或 blob:

boolean CanAddParamsToUrl = true;
        _parameters = new TJSONArray();
        for (DSRESTParameter parameter : ParametersToSend)
            if (CanAddParamsToUrl && isURLParameter(parameter))
                URL += encodeURIComponent(parameter) + '/';
            else // add the json representation in the body
            {
                CanAddParamsToUrl = false;
                parameter.getValue().appendTo(_parameters);
            }

并使用 _parameters 构建主体:

TJSONObject body = new TJSONObject();
                body.addPairs("_parameters", _parameters);
                p.setEntity(new StringEntity(body.toString(), "utf-8"));

我无权访问服务器端,也不知道那里会发生什么。当我发送 JSON 对象或任何其他字符串时,服务器返回 ok,但只要我压缩 JSON 并发送它,服务器就会返回错误 500,提示“无法将输入 JSON 转换为流”。我认为它所指的 JSON 是正文而不是文件中的 JSON 字符串。

从代码的最后一部分,我可以看到为什么字符串会起作用,但我不知道如何使用当前代码按要求发送 zip 文件。反正有没有使用这个代码?还是我应该改变它?如果是这样,怎么做?有谁知道这是否是一个错误?

标签: javajsondelphihttp-posttstream

解决方案


推荐阅读