java – 如何将JSON对象流式传输到HttpURLConnection POST请求

前端之家收集整理的这篇文章主要介绍了java – 如何将JSON对象流式传输到HttpURLConnection POST请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我看不到这段代码有什么问题:
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

在服务器上,我没有收到任何帖子内容,零长度的字符串.

@R_404_323@

尝试
...
httpCon.setRequestMethod("POST");
httpCon.connect(); // Note the connect() here
...
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os,"UTF-8");
...    
osw.write(msg.toString());
osw.flush();
osw.close();

发送数据.

检索数据尝试:

BufferedReader br = new BufferedReader(new InputStreamReader( httpCon.getInputStream(),"utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
    sb.append(line + "\n");
}
br.close();
System.out.println(""+sb.toString());
原文链接:https://www.f2er.com/java/122388.html

猜你在找的Java相关文章