How to stream a JSON object to a HttpURLConnection POST request

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

    Follow this example:

    public static PricesResponse getResponse(EventRequestRaw request) {
    
        // String urlParameters  = "param1=a¶m2=b¶m3=c";
        String urlParameters = Piping.serialize(request);
    
        HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters);
    
        PricesResponse response = null;
    
        try {
            // POST
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(urlParameters);
            writer.flush();
    
            // RESPONSE
            BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8));
            String json = Buffering.getString(reader);
            response = (PricesResponse) Piping.deserialize(json, PricesResponse.class);
    
            writer.close();
            reader.close();
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        conn.disconnect();
    
        System.out.println("PricesClient: " + response.toString());
    
        return response;
    }
    
    
    public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters) {
    
        return RestClient.getConnection(endPoint, "POST", urlParameters);
    
    }
    
    
    public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters) {
    
        System.out.println("ENDPOINT " + endPoint + " METHOD " + method);
        HttpURLConnection conn = null;
    
        try {
            URL url = new URL(endPoint);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(method);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "text/plain");
    
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        return conn;
    }
    

提交回复
热议问题