1

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?

Alevtina
  • 147
  • 11
  • Does this answer your question? [Adding header for HttpURLConnection](https://stackoverflow.com/questions/12732422/adding-header-for-httpurlconnection) – cfrick Dec 01 '20 at 06:51
  • @cfrick, no I receive error: No signature of method: static java.util.Base64.encode() is applicable for argument types: ([B, java.lang.Integer) values: [[117, 115, 101, 114, 49, 58, 117, 115, 101, 114, 49], 0] – Alevtina Dec 01 '20 at 07:03
  • `new String(Base64.getEncoder().encode("secret".getBytes()))` - as in the accepted answer – cfrick Dec 01 '20 at 07:10

1 Answers1

3

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())
...
gigalul
  • 416
  • 3
  • 13