将带文件的cUrl转换为Android HttpUrlConnection

时间:2016-06-14 07:14:03

标签: android curl httpurlconnection put

从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时,即使我将用户代理设置为curl用户代理,也没有Access-Control-Allow-Methods使用c.getHeaderField()。相反,该字段只是Allow,它缺少PUT。

1 个答案:

答案 0 :(得分:0)

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

一个问题是Android充满了mySecretWeirdProtocolHandler()NastyBugNobodyCaresAbout.classpackage.LetMePunchYouInTheFace等内容;所以我最终看着一切都不知道是不是我或他们,这是一个压力很大的好时光。