我正在使用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.
我没有找到任何解决方案,我该如何解决?
答案 0 :(得分:1)
@FormUrlEncoded
。这些参数被编码为正文,您可以拥有自己的。它看起来不像您正在使用和表单参数,因此请删除@FormUrlEncoded
。另外,我建议使用GSON将POJO转换为@Body
的JSON。看起来您正在使用改造1并尝试发送原始String
。 Retrofit将尝试为您编写JSON编码,这意味着您最终会将您发送的对象包含在" ..."中。如果您想发送原始字符串,请在改造1中查看at this answer选项。