【发布时间】:2014-02-23 20:57:08
【问题描述】:
我看不出这段代码有什么问题:
JSONObject msg; //passed in as a parameter to this method
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setUseCaches(false);
httpCon.setRequestProperty( "Content-Type", "application/json" );
httpCon.setRequestProperty("Accept", "application/json");
httpCon.setRequestMethod("POST");
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
msg.write(osw);
osw.flush();
osw.close();
os.close(); //probably overkill
在服务器上,我根本没有收到任何帖子内容,一个零长度的字符串。
【问题讨论】:
-
我知道它看起来很奇怪,但是 JSONObject 类有一个 write 方法,您可以将 Writer 对象传递给该方法,并且该类将自身写入流中。这比转换为字符串然后写入字符串要高效得多。在这种情况下,这并没有真正的区别,我们可以将任何东西蒸到 Writer 上,测试是一样的。错误是关于获取连接的。
标签: java post httpurlconnection