【问题标题】:Convert cUrl put with file to Android HttpUrlConnection将带有文件的 cUrl 转换为 Android HttpUrlConnection
【发布时间】:2016-06-14 07:14:03
【问题描述】:

从 cUrl 迁移到 Android 有几个问题,但我发现没有一个涉及文件上传。

此 CUrl 请求有效:

$ curl -X PUT -u user:password --data-binary @myfile.pdf "https://example.com/myurl?id=myid&filename=myfile.pdf&title=My+Title&mimetype=application/pdf"

我正在尝试:

String url = "https://example.com/myurl?id=myid&filename=myfile.pdf&title=My+Title&mimetype=application/pdf";
String fileUrl = "myfile.pdf";
String userPassword = "user:password";
String userpass = Base64.encodeToString(userPassword.getBytes(), Base64.DEFAULT);

File f = new File(fileUrl);
    if(f.isFile()) {
        HttpURLConnection c = null;
        URL u = null;
        try {
            u = new URL(url);
                c = (HttpURLConnection) u.openConnection();
            c.setRequestProperty("Authorization", "Basic " + userpass);
            c.setDoOutput(true);
            c.setRequestMethod("PUT");
            c.setRequestProperty("Content-Type", "multipart/form-data");

            FileInputStream fis = new FileInputStream(f);
            long fl = f.length();
            output(fis, c.getOutputStream(), fl);
        } catch (Exception e) {
            e.printStackTrace();
        }

output(fis, c.getOutputStream(), fl); 将 inputStream 写入 outputStream 然后关闭/刷新两者。

我收到了method not allowed 的回复,有人知道我做错了什么吗?

编辑:(对我来说)他们的响应标头具有:Allow: POST,OPTIONS,GET,HEAD 但使用 curl 的 PUT 有效。

编辑两个

当使用 curl 我实际上得到:

Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE

但是在使用HttpUrlConnection时,即使我将user-agent设置为curl用户代理,也没有Access-Control-Allow-Methods使用c.getHeaderField()。相反,该字段只是 Allow,并且缺少 PUT。

【问题讨论】:

    标签: android curl httpurlconnection put


    【解决方案1】:

    好吧,这太愚蠢了。上面的代码没有任何问题,但是 api 显示使用了 .net 域,该域未配置为接受 PUT。当我注意到一切正常时,开发人员向我发送了一个使用 .com 域的 curl 示例。

    一个问题是Android充满了mySecretWeirdProtocolHandler()NastyBugNobodyCaresAbout.classpackage.LetMePunchYouInTheFace之类的东西;所以我最终一下子看着所有东西,不知道是我还是他们,度过了一段充满压力的美好时光。

    【讨论】:

      猜你喜欢
      • 2017-02-13
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 2016-11-19
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      相关资源
      最近更新 更多