bsky
bsky

Reputation: 20222

Find out how Postman request is constructed and replicate in java

I am making a GET request using Postman. As part of the request, I selected Authorization, Basic Auth and then I filled in my username and password.

The request was successful. Now, I would like to replicate this in Java code.

In Java I tried this:

URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
String userCredentials = "username:password";
myURLConnection.setRequestProperty ("Authorization", userCredentials);

Although this seems to be similar to what Postman does, it doesn't work.

How can I replicate the above Postman request in Java?

Upvotes: 0

Views: 1993

Answers (2)

bn.
bn.

Reputation: 7949

There is a link on the Postman UI to generate code snippets for Java using OkHttp or Unirest, or for other languages and libraries.

Step 1 enter image description here

Step 2

enter image description here

Upvotes: 3

Mena
Mena

Reputation: 48404

As this article (chapter "How Basic Authentication Works") points out, the header needs to base64 encode the username:password for basic authentication.

In Postman, you can see the encoded value in the headers' bulk edit:

enter image description here

You can lookup Java's own Base64 utility class to do so.

Edit

If you either use Java's OkHttp or Unirest frameworks, you can use the solution underlined by bn. to quickly use a ready-made code template, instead of doing it "by hand".

Upvotes: 1

Related Questions