Java - sending HTTP parameters via POST method easily

前端 未结 17 1758
借酒劲吻你
借酒劲吻你 2020-11-21 05:54

I am successfully using this code to send HTTP requests with some parameters via GET method

void sendRequest(String request)
{
            


        
17条回答
  •  粉色の甜心
    2020-11-21 06:57

    Try this pattern:

    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;
    }
    

提交回复
热议问题