【发布时间】:2013-04-08 14:53:55
【问题描述】:
我正在向发送 JSON 字符串的 HTTP 服务器发出请求。我使用 Gson 序列化和反序列化 JSON 对象。今天我观察到这种非常奇怪的行为,我不明白。
我有:
String jsonAsString = gson.toJson(jsonAsObject).replace("\"", "\\\"");
System.out.println(jsonAsString);
输出就是这样:
{\"content\":\"Literal\",\"pos\":{\"left\":20,\"top\":20}}
现在我使用从HttpURLConnection 获得的OutputStreamWriter 来发出带有JSON 有效负载的HTTP、PUT 请求。上述请求工作正常:
os.write("{\"content\":\"Literal\",\"pos\":{\"left\":20,\"top\":20}}");
但是,当我说:
os.write(jsonAsString);
...请求不起作用(此服务器不返回任何错误,但我可以看到,当将 JSON 编写为字符串对象时,它没有做它应该做的事情)。在字符串对象上使用字符串文字时是否有区别。我做错了吗?
这里是sn-p:
public static void EditWidget(SurfaceWidget sw, String widgetId) {
Gson gson = new Gson();
String jsonWidget = gson.toJson(sw).replace("\"", "\\\"");
System.out.println(jsonWidget);
try {
HttpURLConnection hurl = getConnectionObject("PUT", "http://fltspc.itu.dk/widget/5162b1a0f835c1585e00009e/");
hurl.connect();
OutputStreamWriter os = new OutputStreamWriter(hurl.getOutputStream());
//os.write("{\"content\":\"Literal\",\"pos\":{\"left\":20,\"top\":20}}");
os.write(jsonWidget);
os.flush();
os.close();
System.out.println(hurl.getResponseCode());
} catch (IOException e) {
e.printStackTrace();
}
}
【问题讨论】:
标签: java json httpurlconnection