使用Retrofit发布到Google Cloud Messaging

时间:2015-11-15 13:16:56

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

我正在使用HttpURLConnection POST 消息发送到GCM,例如:

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();
}

现在我想将Retrofit用于 POST 消息到GCM
我试过了:

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

我在 data 中发送了json字符串,但它始终因此错误而失败:

@Body parameters cannot be used with form or multi-part encoding.

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

1 个答案:

答案 0 :(得分:1)

如果要发送表单参数,则使用

@FormUrlEncoded。这些参数被编码为正文,您可以拥有自己的。它看起来不像您正在使用和表单参数,因此请删除@FormUrlEncoded。另外,我建议使用GSON将POJO转换为@Body的JSON。看起来您正在使用改造1并尝试发送原始String。 Retrofit将尝试为您编写JSON编码,这意味着您最终会将您发送的对象包含在" ..."中。如果您想发送原始字符串,请在改造1中查看at this answer选项。