How to stream a JSON object to a HttpURLConnection POST request

前端 未结 5 2036
鱼传尺愫
鱼传尺愫 2021-02-05 14:09

I can not see what is wrong with this code:

JSONObject msg;  //passed in as a parameter to this method

HttpURLConnection httpCon = (HttpURLConnection) url.openC         


        
5条回答
  •  终归单人心
    2021-02-05 15:03

    Try

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

    to send data.

    to retrieve data try:

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

提交回复
热议问题