cURL and HttpURLConnection - Post JSON Data

后端 未结 2 1165
走了就别回头了
走了就别回头了 2020-12-02 12:55

How to post JSON data using HttpURLConnection? I am trying this:

HttpURLConnection httpcon = (HttpURLConnection) ((new URL(\"a url\").openConnection()));
htt         


        
相关标签:
2条回答
  • 2020-12-02 13:00

    OutputStream expects to work with bytes, and you're passing it characters. Try this:

    HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection()));
    httpcon.setDoOutput(true);
    httpcon.setRequestProperty("Content-Type", "application/json");
    httpcon.setRequestProperty("Accept", "application/json");
    httpcon.setRequestMethod("POST");
    httpcon.connect();
    
    byte[] outputBytes = "{'value': 7.5}".getBytes("UTF-8");
    OutputStream os = httpcon.getOutputStream();
    os.write(outputBytes);
    
    os.close();
    
    0 讨论(0)
  • 2020-12-02 13:04

    You may want to use the OutputStreamWriter class.

    final String toWriteOut = "{'value': 7.5}";
    final OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
    osw.write(toWriteOut);
    osw.close();
    
    0 讨论(0)
提交回复
热议问题