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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
  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.

Dmytro Budym user avatar by
Dmytro Budym
·
Feb. 02, 23 · Code Snippet
Like (3)
Save
Tweet
Share
3.37K 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.

Popular on DZone

  • OpenVPN With Radius and Multi-Factor Authentication
  • How To Best Use Java Records as DTOs in Spring Boot 3
  • Low-Code Development: The Future of Software Development
  • Getting a Private SSL Certificate Free of Cost

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: