Warm tip: This article is reproduced from serverfault.com, please click

How to pass your username and password in a get request with groovy?

发布于 2020-12-01 06:45:19

I send GET request and receive error 500

 def baseUrl = new URL(url)
         HttpURLConnection connection = (HttpURLConnection) baseUrl.openConnection();
         connection.addRequestProperty("Authorization", "user1 user1")
         connection.addRequestProperty("Accept", "application/json")
         connection.with {
           doOutput = true
           requestMethod = 'GET'
           println content.text
         }

I am sure that my api work true.

How to pass your username and password in a get request with groovy?

Questioner
Alevtina
Viewed
0
gigalul 2020-12-01 15:19:34

The way you wrote the "Authorization" header is incorrect. For basic authentication, you need to encode the username and password and use it alongside the "Basic" keyword.

import java.net.HttpUrlConnection
import java.net.URL
import java.util.Base64.Encoder

def baseUrl = new URL("https://myurl.com")
def credentials = "user1 user1"
def encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes())
...
connection.addRequestProperty("Authorization", "Basic " + encodedCredentials.toString())
...