DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Hackerman [Comic]
  • Implementing Infinite Scroll in jOOQ
  • What Is Pydantic?
  • How to Do API Testing?

Trending

  • How to Migrate From LangChainGo to Genkit Go
  • SSRF Prevention in C#: Securing File Imports From User-Supplied URLs
  • Why Spark Executors Leave Cores Idle on YARN: A Packing Model for Executor Sizing
  • Beyond the Endpoint: How Agent Cards Enable Discovery, Interoperability, and Trust

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Testing, Deployment, and Maintenance
  3. DevOps and CI/CD
  4. Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts

Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts

Use HTTP Request Plugin in Jenkins pipelines as an alternative to raw CURL commands. See examples of CURL management in a declarative way.

By 
Dmytro Budym
·
Feb. 02, 23 · Code Snippet
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
15.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Have you ever needed to make some HTTP requests in your Jenkins pipeline? How will you do that?

The first that comes to mind is to use the simple CURL command. It's a powerful tool, and it will be fine for simple cases like the usual GET request. But what about more complicated issues? What if you need to execute POST with a huge JSON body and many headers? CURL command will be obscure and not maintainable. Also, it will be hell with escaping quotes and special symbols to make it works in the pipeline.

While last interacting with this hell, I've thought about an alternative and found that - a powerful plugin, HTTP Request.

To use the HTTP Request Plugin, you will need to install it in your Jenkins. This can be done through the Jenkins plugin manager, which allows you to browse and install plugins from the Jenkins interface. Once the plugin is installed, you can use it in pipelines with the keyword httpRequest.

Main features:

  • Request types GET, HEAD, POST, PUT, PATCH, DELETE
  • Expected response code or string content
  • Basic/Form authentication
  • Connection timeout
  • Add custom headers

I've prepared a few examples to compare and contrast both approaches. These examples illustrate the key differences between executing HTTP requests in the pipeline and demonstrate how HTTP Request Plugin may be better suited for specific situations.

By examining these examples, you can better understand each tool's strengths and weaknesses and determine which is the best fit for your needs.

GET Request

CURL

 
stage('Execute Request') {
            steps {
               script {
                    sh "curl https://dummyjson.com/products"
            }
      }
}


Plugin

 
stage('Execute Request') {
	      steps {
	        httpRequest "https://dummyjson.com/products"
	    }
}


Custom Headers

CURL

 
stage('Execute Request') {
      steps {
         script {
              sh "curl --location --request GET 'https://dummyjson.com/auth/products/1' \\\n" +
                 "--header 'Content-Type: application/json' \\\n" +
                 "--header 'Authorization: Bearer YOUR_TOKEN' \\\n" +
                 "--data-raw ''"
            }
      }
}


Plugin

 
stage('Execute Request') {
      steps {
         httpRequest customHeaders: [[name: 'Content-Type', value: 'application/json'],
                                     [name: 'Authorization', value: 'Bearer YOUR_TOKEN']], 
      url: 'https://dummyjson.com/auth/products/1'
    }
}


POST Request With Complex Payload

CURL

 
stage('Execute Request') {
      steps {
         script {
           sh "curl --location --request POST 'https://dummyjson.com/carts/add' \\\n" +
              "--header 'Content-Type: application/json' \\\n" +
              "--data-raw '{\n" +
                       "    \"userId\": \"1\",\n" +
                       "    \"products\": [\n" +
                       "        {\n" +
                       "            \"id\": \"23\",\n" +
                       "            \"quantity\": 5\n" +
                       "        },\n" +
                       "          {\n" +
                       "            \"id\": \"45\",\n" +
                       "            \"quantity\": 19\n" +
                       "        }\n" +
                       "    ]\n" +
                       "}'"

			    }
       }
}


Plugin

 
stage('Execute Request') {
      steps {
         httpRequest contentType: 'APPLICATION_JSON',
           httpMode: 'POST',
           requestBody: '''{
                 "userId": "1",
                 "products": [
                     {"id": "23","quantity": 5},
                     {"id": "45","quantity": 19}
               }''',
           url: 'https://dummyjson.com/carts/add'
     }
}


Response Code and Content Validation

CURL

 
stage('Execute Request') {
      steps {
         script {
              def (String response, int code) = sh(script: "curl -s -w '\\n%{response_code}' https://dummyjson.com/products", returnStdout: true)
                          .trim()
                          .tokenize("\n")
                          
              if(code != "200") {
                  throw new Exception("Status code doesn't match. Received: $code" )
              }
							
							if(!response.contains("userId")){
                   throw new Exception("Very strange message\n" + response)
              }
        }
    }
}


Plugin

 
stage('Execute Request') {
            steps {
              httpRequest url:"https://dummyjson.com/products", 
							validResponseCodes:'200',
							validResponseContent:'userId'
      }
}


The validation rule will fail to build with the following:

hudson.AbortException: Fail: Status code 500 is not in the accepted range: 200 

hudson.AbortException: Fail: Response doesn't contain expected content 'userId'

Conclusion

HTTP Request Plugin is a valuable tool for Jenkins users. It allows you to easily send HTTP requests as part of your Jenkins jobs, enabling you to automate tasks and integrate Jenkins with other tools and services. The plugin's user-friendly interface and additional functionality for handling responses make it easy to use and powerful. If you are looking to expand the capabilities of your Jenkins instance and streamline your workflow, the Jenkins HTTP Request Plugin is definitely worth considering.

Feel free to read the official documentation and visit the GitHub repository.

CURL JSON Groovy (programming language) Id (programming language) Jenkins (software) Pipeline (software) POST (HTTP) Requests workflow Data Types

Opinions expressed by DZone contributors are their own.

Related

  • Hackerman [Comic]
  • Implementing Infinite Scroll in jOOQ
  • What Is Pydantic?
  • How to Do API Testing?

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook