【问题标题】:POST to Google Cloud Messaging with Retrofit使用 Retrofit 发布到 Google Cloud 消息传递
【发布时间】:2016-02-16 15:36:09
【问题描述】:

我正在使用HttpURLConnectionGCM 发送POST 消息,例如:

try {
    URL url = new URL(GCM_SERVER_URL);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Authorization", "key=" + apiKey);
    conn.setDoOutput(true);

    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

    DataOutputStream dataOutputStream = new DataOutputStream(conn.getOutputStream());

    mapper.writeValue(dataOutputStream, content);

    dataOutputStream.flush();
    dataOutputStream.close();

    // Get the response
    int responseCode = conn.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    System.out.println(response.toString());
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

现在我想使用 RetrofitPOST 消息发送到 GCM
我试过了:

@Headers("Content-Type: application/json")
@FormUrlEncoded
@POST("/")
public GCMObject GCMAuthorization(@Header("Authorization") String apiKey,
                                  @Body String data
);

我在 data 中发送了 json 字符串,但它总是失败并出现此错误:

@Body 参数不能与表单或多部分编码一起使用。

我没有找到任何解决方案,我该如何解决?

【问题讨论】:

    标签: java android post google-cloud-messaging retrofit


    【解决方案1】:

    @FormUrlEncoded 用于发送表单参数。这些参数被编码为body,你可以有你自己的。它看起来不像你在使用和表单参数,所以删除@FormUrlEncoded。此外,我建议使用 GSON 将您的 POJO 转换为 JSON 以获取 @Body。看起来您正在使用改造 1 并尝试发送原始 String。 Retrofit 将尝试为您进行 JSON 编码,这意味着您最终将发送包裹在“...”中的对象。如果您想发送原始字符串,请查看 at this answer 以了解您在改造 1 中的选项。

    【讨论】:

    • 谢谢,有点不同的问题,我发帖给 GCM,将“Content-Type:...”和“Authorization:key=A...”添加到“Header”,回复是“400 InvalidTokenFormat”,互联网上没有解决方案,HttpURLConnection 工作正常,但改造失败并出现此错误。是改造编码错误还是您对此错误有任何想法?
    • 我的猜测是,当您在 UrlConnection 中设置标题时,您会在前面加上“key=”,因此请确保对改造做同样的事情 - GCMAuthorization.("key="+apiKey, data)
    • 您是否按照链接答案中的说明将@Body 更改为使用TypedInput?您将在正文中发送无效的 JSON。
    • 我认为您在新实现中缺少“to”字段。将其添加到您的 GCMRequest 对象中。
    • 它不能像 doc 中那样使用“to”,而是使用“registration_ids”和 HttpURLConnection。但是当我更改 HttpURLConnection -> Retrofit 失败时,我认为这与正文内容或我的请求参数无关。 GCM 不接受“授权”格式并返回“400 InvalidTokenFormat”,我与 HttpURLConnection 使用相同的密钥成功,但改造失败。比我认为改造错误编码标头参数。这些时候我很困惑,谷歌没有添加任何关于 GCM 响应“400 InvalidTokenFormat”的文档...
    猜你喜欢
    • 2019-11-06
    • 1970-01-01
    • 2015-09-16
    • 2020-09-15
    • 2015-03-30
    • 2014-08-02
    • 2012-07-12
    • 1970-01-01
    • 2015-03-23
    相关资源
    最近更新 更多