Java - sending HTTP parameters via POST method easily

前端 未结 17 2030
借酒劲吻你
借酒劲吻你 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:45

    I higly recomend http-request built on apache http api.

    For your case you can see example:

    private static final HttpRequest HTTP_REQUEST = 
          HttpRequestBuilder.createPost("http://example.com/index.php", String.class)
               .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
               .build();
    
    public void sendRequest(String request){
         String parameters = request.split("\\?")[1];
         ResponseHandler responseHandler = 
                HTTP_REQUEST.executeWithQuery(parameters);
    
       System.out.println(responseHandler.getStatusCode());
       System.out.println(responseHandler.get()); //prints response body
    }
    

    If you are not interested in the response body

    private static final HttpRequest HTTP_REQUEST = 
         HttpRequestBuilder.createPost("http://example.com/index.php").build();
    
    public void sendRequest(String request){
         ResponseHandler responseHandler = 
               HTTP_REQUEST.executeWithQuery(parameters);
    }
    

    For general sending post request with http-request: Read the documentation and see my answers HTTP POST request with JSON String in JAVA, Sending HTTP POST Request In Java, HTTP POST using JSON in Java

提交回复
热议问题