Search code examples
javajsonspringpostbasic-authentication

Enter credentials then post JSON to api java


I have been trying to figure out a way to post a JSON to a external api. The issue is a don't want to hardcode the username and password but rather have it be used by anyone who has valid credentials to the API.I have code that works for hardcoded credentials but I want the user to enter the the username and password per request. I want to use the basic auth browser dialogue to capture the credentials then post JSON but I can't figure it out.

here is my current code

public class RestService {
    String Username="admin";
    String Password="pass";

  public String createPost() throws AuthenticateException,ClientHandlerException {

String url = "https://someapi.net/rest/api/2/issue/";

Client client = Client.create ();

client.addFilter (new HTTPBasicAuthFilter(Username, Password));
WebResource webResource= client.resource(url);
//--INPUT is formatted a bit different In my app but I just can't show it
String input = "{
    "fields": {
       "project":
       {
          "key": "TEST"
       },
       "summary": "REST ye merry gentlemen.",
       "description": "Creating of an issue using project keys and issue type names using the REST API",
       "issuetype": {
          "name": "Bug"
       }
   }
}"

ClientResponse response = webResource.type("application/json").post(ClientResponse.class,input);
string output = response.getEntity(String.Class)

I found this and was told it might work but I'm not sure where I enter that into my code.

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
String encoded = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));  //Java 8
connection.setRequestProperty("Authorization", "Basic "+encoded);

Solution

  • It seems that you want to create an Jira issue with basic authentication by using Jersey Client API, then you can pass the credential in header as follows:

    String encoded = Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
    
    ClientResponse response = webResource.type("application/json")
            .header("Authorization", "Basic " + encoded) // put the credential in header
            .post(ClientResponse.class,input);