How to stream a JSON object to a HttpURLConnection POST request

前端 未结 5 2037
鱼传尺愫
鱼传尺愫 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:08

    HttpURLConnection is cumbersome to use. With DavidWebb, a tiny wrapper around HttpURLConnection, you can write it like this:

    JSONObject msg;  //passed in as a parameter to this method
    
    Webb webb = Webb.create();
    JSONObject result = webb.post("http://my-url/path/to/res")
        .useCaches(false)
        .body(msg)
        .ensureSuccess()
        .asJsonObject()
        .getBody();
    

    If you don't like it, there is a list of alternative libraries on the link provided.

    Why should we all write the same boilerplate code every day? BTW the code above is more readable and less error-prone. HttpURLConnection has an awful interface. This has to be wrapped!

提交回复
热议问题