【问题标题】:What's wrong I did to send a batch request to google?我向谷歌发送批量请求做错了什么?
【发布时间】:2014-11-28 12:59:52
【问题描述】:

我尝试使用 OkHttp 向 Google 发送批处理请求,但我总是收到错误 500 和未知错误作为响应。

这是我的代码,令牌来自 GoogleAuthUtil。

    MultipartBuilder multipartBuilder = new MultipartBuilder();
    MediaType http = MediaType.parse("application/http");
    MediaType mixed = MediaType.parse("multipart/mixed");
    multipartBuilder.addPart(RequestBody.create(http, "GET https://www.googleapis.com/gmail/v1/users/me/messages"));
    multipartBuilder.type(mixed);
    Request request = new Request.Builder()
            .url("https://www.googleapis.com/batch")
            .header("Authorization", " Bearer " + token)
            .post(multipartBuilder.build())
            .build();

    try{
        Response response = client.newCall(request).execute();
        String res = response.body().string();
    }
    catch (IOException e){
        e.printStackTrace();
    }

【问题讨论】:

    标签: java google-api gmail-api okhttp


    【解决方案1】:

    最后,我解决了这个问题。除了一行之外,所有代码都没有问题:

    multipartBuilder.addPart(RequestBody.create(http, "GET https://www.googleapis.com/gmail/v1/users/me/messages"));
    

    应该先转换为byte[],然后再调用类似的方法,不要忘记\n。

    byte[] request = (https://www.googleapis.com/gmail/v1/users/me/messages).getBytes();
    RequestBody partRequest = RequestBody.create(HTTP, request);
    

    我在 OkHttp 源代码中发现了问题。

    public static RequestBody create(MediaType contentType, String content) {
      Charset charset = Util.UTF_8;
      if (contentType != null) {
        charset = contentType.charset();
        if (charset == null) {
          charset = Util.UTF_8;
          contentType = MediaType.parse(contentType + "; charset=utf-8");
        }
      }
      byte[] bytes = content.getBytes(charset);
      return create(contentType, bytes);
    }
    

    问题是要添加到 Content-Type 的字符集。它会产生 500 错误。

    【讨论】:

      猜你喜欢
      • 2016-01-29
      • 1970-01-01
      • 2011-10-22
      • 2015-12-15
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多