【问题标题】:How to add a file parameter inside scribe oauthrequest?如何在 scribe oauthrequest 中添加文件参数?
【发布时间】:2013-01-28 14:20:07
【问题描述】:

如标题所述

如果输入的是文件,oauthRequest.addBodyParameter(key, value) 似乎效果不佳

我尝试执行以下操作将文件强制转换为字符串,但无济于事:

File f = new File("xyz.png");
InputStream is = new FileInputStream(f);
int intValue = -1;
String value = "";
do {
   intValue = is.read();
   if (intValue != -1) {
      char c = (char) intValue;
      value += c;
   }
} while (intValue != -1);

顺便说一句,我正在尝试以编程方式将图像上传到 Flickr(不确定是否有更直接的方法)

【问题讨论】:

    标签: java file file-upload oauth scribe


    【解决方案1】:

    当然addBodyParameter 不会起作用,因为您不想包含正文参数,您想创建一个多部分 http 请求。

    Scribe 并没有让您轻松做到这一点,原因是 Apis 支持文件上传并不是很常见,而其他库很好地做到了这一点。 (当 scribe 被迁移到使用 apache commons http 时,每个人都会变得更容易)

    正如@Chris 所说,尽管 (+1) 您可以并鼓励您使用 addPayload 方法,但您需要自己创建多部分请求。对不起。

    免责声明:我是图书馆作者。

    【讨论】:

    • 如果我只是使用 addPayload 放置手动创建的多部分请求,或者我是否需要更改 org.scribe.model.Request 中的某些内容,它会起作用吗?(因为它已经设置了 Content-Type 标头.)
    【解决方案2】:

    我认为您在这里遇到的问题是您如何读取图像文件。将图像表示为由您一次读取一个字符构建的字符串会导致问题。虽然 char 是一个字节,但 Java 中的字符串是 UTF-8。当您输出一个字符串时,您不仅会获得用于构建它的字符,还会获得 UTF-8 表示形式。

    所以我自己没有尝试过,您是否尝试过使用public void addPayload(byte[] payload) 方法而不是addBodyParameter(key, value)?这似乎是马上去做。

    【讨论】:

    • 但我还需要一个密钥(即“照片”,用于将图像上传到 Flickr)。所以最初我尝试了 oauthRequest.addBodyParameter("photo", imageFileAsString); ,当然无济于事
    【解决方案3】:

    补充一下@Pablo 所说的,如果您已经在使用 Apache Commons HTTP 客户端库,则可以使用您的 MultipartEntity 对象来处理多部分请求格式:

    MultipartEntity reqEntity = new MultipartEntity();
    // add your ContentBody fields as normal...
    
    // Now, pull out the contents of everything you've added and set it as the payload
    ByteArrayOutputStream bos = new ByteArrayOutputStream((int)reqEntity.getContentLength());
    reqEntity.writeTo(bos);
    oAuthReq.addPayload(bos.toByteArray());
    
    // Finally, set the Content-type header (with the boundary marker):
    Header contentType = reqEntity.getContentType();
    oAuthReq.addHeader(contentType.getName(), contentType.getValue());
    
    // Sign and send like normal:
    service.signRequest(new Token(oAuthToken, oAuthSecret), oAuthReq);
    Response oauthResp = oAuthReq.send();
    

    当然,这样做的缺点是您需要将整个内容主体读入内存中的byte[],因此如果您要发送巨大的文件,这可能不是最佳选择。但是,对于小型上传,这对我有用。

    【讨论】:

      猜你喜欢
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多