Java - sending HTTP parameters via POST method easily

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

    This answer covers the specific case of the POST Call using a Custom Java POJO.

    Using maven dependency for Gson to serialize our Java Object to JSON.

    Install Gson using the dependency below.

    
      com.google.code.gson
      gson
      2.8.5
      compile
    
    

    For those using gradle can use the below

    dependencies {
    implementation 'com.google.code.gson:gson:2.8.5'
    }
    

    Other imports used:

    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.*;
    import org.apache.http.impl.client.CloseableHttpClient;
    import com.google.gson.Gson;
    

    Now, we can go ahead and use the HttpPost provided by Apache

    private CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost("https://example.com");
    
    Product product = new Product(); //custom java object to be posted as Request Body
        Gson gson = new Gson();
        String client = gson.toJson(product);
    
        httppost.setEntity(new StringEntity(client, ContentType.APPLICATION_JSON));
        httppost.setHeader("RANDOM-HEADER", "headervalue");
        //Execute and get the response.
        HttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            throw new InternalServerErrorException("Post fails");
        }
        Response.Status responseStatus = Response.Status.fromStatusCode(response.getStatusLine().getStatusCode());
        return Response.status(responseStatus).build();
    

    The above code will return with the response code received from the POST Call

提交回复
热议问题