google-api - 通过 Google HTTP 客户端对 Box API 的多部分请求

标签 google-api box-api google-http-client

我正在尝试调用此特定方法 http://developers.box.com/docs/#files-upload-a-file在 Google HTTP 客户端库 v1.14.1 的帮助下,在 Box API 中。目前我看不到这样做的方法。

如果我使用 http://hc.apache.org/httpclient-3.x/methods/multipartpost.html ,我会添加 2 项 StringPart 和 1 项 FilePart。

在 Google HTTP 客户端库中,我只看到 MultipartContent 和 Part 类似乎无法处理纯名称/值对,如上面引用的 StringPart 。

以下是 Apache HTTP 客户端示例的摘录:

HttpPost httppost = new HttpPost("http://localhost:8080" +
                "/servlets-examples/servlet/RequestInfoExample");

FileBody bin = new FileBody(new File(args[0]));
StringBody comment = new StringBody("A binary file of some kind");

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);

httppost.setEntity(reqEntity);

我想完成类似的事情,但使用 Google HTTP 客户端。欢迎大家提出意见!

最佳答案

经过一番调查,我发现 Box API 需要 Content-Type: multipart/form-data 并适本地构建请求。我使用的 Google HTTP 客户端版本无法实现,所以我自己实现了 MultipartFormDataContent 类,它非常适合库。这是该类的完整列表。也许它可以包含在库中。

/*
 * Copyright (c) 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/**
 * This is a modification of com.google.api.client.http.MultipartContent from
 * Google HTTP Client library to support multipart/form-data requests.
 *
 * The original author is Yaniv Inbar.
 */
public class MultipartFormDataContent extends AbstractHttpContent {
    private static final String NEWLINE = "\r\n";
    private static final String TWO_DASHES = "--";
    private ArrayList<Part> parts = new ArrayList<Part>();

    public MultipartFormDataContent() {
        super(new HttpMediaType("multipart/form-data").setParameter("boundary", "__END_OF_PART__"));
    }

    @Override
    public void writeTo(OutputStream out) throws IOException {
        Writer writer = new OutputStreamWriter(out, getCharset());
        String boundary = getBoundary();
        for (Part part : parts) {
            HttpHeaders headers = new HttpHeaders().setAcceptEncoding(null);
            if (part.headers != null) {
                headers.fromHttpHeaders(part.headers);
            }
            headers.setContentEncoding(null)
                   .setUserAgent(null)
                   .setContentType(null)
                   .setContentLength(null);
            // analyze the content
            HttpContent content = part.content;
            StreamingContent streamingContent = null;
            String contentDisposition = String.format("form-data; name=\"%s\"", part.name);
            if (part.filename != null) {
                headers.setContentType(content.getType());
                contentDisposition += String.format("; filename=\"%s\"", part.filename);
            }
            headers.set("Content-Disposition", contentDisposition);
            HttpEncoding encoding = part.encoding;
            if (encoding == null) {
                streamingContent = content;
            } else {
                headers.setContentEncoding(encoding.getName());
                streamingContent = new HttpEncodingStreamingContent(content, encoding);
            }
            // write separator
            writer.write(TWO_DASHES);
            writer.write(boundary);
            writer.write(NEWLINE);
            // write headers
            HttpHeaders.serializeHeadersForMultipartRequests(headers, null, null, writer);
            // write content
            if (streamingContent != null) {
                writer.write(NEWLINE);
                writer.flush();
                streamingContent.writeTo(out);
                writer.write(NEWLINE);
            }
        }
        // write end separator
        writer.write(TWO_DASHES);
        writer.write(boundary);
        writer.write(TWO_DASHES);
        writer.write(NEWLINE);
        writer.flush();
    }

    @Override
    public boolean retrySupported() {
        for (Part part : parts) {
            if (!part.content.retrySupported()) {
                return false;
            }
        }
        return true;
    }

    @Override
    public MultipartFormDataContent setMediaType(HttpMediaType mediaType) {
        super.setMediaType(mediaType);
        return this;
    }

    /**
     * Adds an HTTP multipart part.
     *
     * <p>
     * Overriding is only supported for the purpose of calling the super
     * implementation and changing the return type, but nothing else.
     * </p>
     */
    public MultipartFormDataContent addPart(Part part) {
        parts.add(Preconditions.checkNotNull(part));
        return this;
    }

    /**
     * Sets the boundary string to use.
     *
     * <p>
     * Defaults to {@code "END_OF_PART"}.
     * </p>
     *
     * <p>
     * Overriding is only supported for the purpose of calling the super
     * implementation and changing the return type, but nothing else.
     * </p>
     */
    public MultipartFormDataContent setBoundary(String boundary) {
        getMediaType().setParameter("boundary", Preconditions.checkNotNull(boundary));
        return this;
    }

    /**
     * Single part of a multi-part request.
     *
     * <p>
     * Implementation is not thread-safe.
     * </p>
     */
    public static final class Part {
        private String name;
        private String filename;
        private HttpContent content;
        private HttpHeaders headers;
        private HttpEncoding encoding;

        public Part setContent(HttpContent content) {
            this.content = content;
            return this;
        }

        public Part setHeaders(HttpHeaders headers) {
            this.headers = headers;
            return this;
        }

        public Part setEncoding(HttpEncoding encoding) {
            this.encoding = encoding;
            return this;
        }

        public Part setName(String name) {
            this.name = name;
            return this;
        }

        public Part setFilename(String filename) {
            this.filename = filename;
            return this;
        }
    }
}

关于google-api - 通过 Google HTTP 客户端对 Box API 的多部分请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15996719/

相关文章:

oauth-2.0 - OAuth2 中的永久访问 token

java - Box java sdk - 为 BoxItem 生成 Box URL

java - Robospice 缓存对象始终为空

java - 列出不同用户的 Google 日历 Activity

c# - 如何使用 C# SDK 访问与我共享的 Box 文件夹

java - 如何增加 Google HTTP 客户端中的 ReadTimeout

java - 如何使用 Java 的 HTTP 客户端库设置应用程序名称?

google-api - 无法在没有已知用户的情况下执行 GSuite 服务帐户目录 API 调用

android - 如何使用 intellij idea 调试已签名的应用程序?

java - Google 不返回某些日历的时区