Answers for "maven http simple client post example with body"

0

maven http simple client post example with body

package javainspires.apachehttpclientexamples;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;

/**
 * 
 * @author javainspires
 *
 */
public class SimpleHttpPOSTRequestDemo {

 public static void main(String[] args) {
  try {
   // Http POST Request

   // create http client object
   HttpClient httpClient = HttpClients.createDefault();

   // create http POST request
   HttpPost httpPost = new HttpPost();

   // set request URI ro thr created request object
   httpPost.setURI(new URI("https://reqres.in/api/users"));

   // construct JSON body
   String requestBody = "{    \"name\": \"morpheus\",    \"job\": \"leader\"}";

   // convert request body into string entity

   StringEntity stringEntity = new StringEntity(requestBody);

   // set stringEntity to the created post request
   httpPost.setEntity(stringEntity);

   // execute created httpPost request
   HttpResponse httpResponse = httpClient.execute(httpPost);

   System.out.println("Status Code - " + httpResponse.getStatusLine().toString());

  } catch (URISyntaxException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (UnsupportedEncodingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

}
Posted by: Guest on October-21-2021

Code answers related to "maven http simple client post example with body"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language