Search code examples
javacurltrace

How to convert a cURL call into a Java URLConnection call


I have a cURL command:

curl -d '{"mobile_number":"09178005343", "pin":"1111"}' -H "Content:Type: application/json" -H "X-Gateway-Auth:authentication" -X POST https://localhost:9999/api/traces/%2f/login

I need to create an HTTP Request in Java API which will do the same thing. I don't have any idea regarding this. Thank you in advance for those who will take time to respond.


Solution

  • There are multiple ways to do it. Firstly, since you want to send a JSON object, you might want to use a JSON library, for example, Google's gson. But to make it easy you can just send the request as a String. Here is a sample code that sends your JSON to your URL.

    HttpClient httpClient = HttpClientBuilder.create().build(); 
    
    try {
    
        HttpPost request = new HttpPost("https://localhost:9999/api/traces/%2f/login");
        StringEntity params =new StringEntity("{\"mobile_number\":\"09178005343\", \"pin\":\"1111\"");
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
    
        //Do what you want with the response
    
    }catch (Exception ex) {
    
        //If exception occurs handle it
    
    } finally {
         //Close the connection 
    }