Pages

http post request in java

http post request in java

  • In java there are many libraries to verify http post method.one of the library easy to use httpClient.
  • An HttpClient can be used to send requests and retrieve their responses. An HttpClient is created through a builder. The builder can be used to configure per-client state, like: the preferred protocol version ( HTTP/1.1 or HTTP/2 ), whether to follow redirects, a proxy, an authenticator, etc. Once built, an HttpClient is immutable, and can be used to send multiple requests.
  • In order to use httpClient download httpClient jar from mvn repository or add dependency in your project.
Key notes about POST method:
  • POST method is used to data to server (for creation or updation of data)
  • POST request can never be cached, bookmarked and remained in browser history.
  • POST request can't be bookmarked
  • POST requests do not remain in browser history
  • POST requests have no length restrictions.
import org.apache.http.HttpResponse;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class PostDemo {
public static void main(String[] args) throws Exception {

HttpClient httpclient = HttpClientBuilder.create().build();

// Creating a HttpPost object
HttpPost httppost = new HttpPost("https://reqres.in/api/login");

System.out.println("Request Type: " + httppost.getMethod());


//adding headers
httppost.addHeader("Content-Type", "application/json");


String body = "{" + " \"email\": \"eve.holt@reqres.in\"," + " \"password\": \"cityslicka\"" + "}";

StringEntity reqBody = new StringEntity(body);
httppost.setEntity(reqBody);

// Executing the post request
HttpResponse httpresponse = httpclient.execute(httppost);

//converting post api response to string
String jsonString = EntityUtils.toString(httpresponse.getEntity());
//convert api response to JSON object
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(jsonString);
String accessToken = (String) json.get("token");


System.out.println("Token from server=" + accessToken);
}
}
Output:
http post request in java
http post request in java

Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.