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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

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

Trending

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • The Ultimate Guide to Code Formatting: Prettier vs ESLint vs Biome
  • Agentic AI Systems: Smarter Automation With LangChain and LangGraph
  • How to Format Articles for DZone
  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 user avatar
Dmytro Budym
·
Feb. 02, 23 · Code Snippet
Likes (4)
Comment
Save
Tweet
Share
12.6K Views

Join the DZone community and get the full member experience.

Join For Free

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
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!