Home > OS >  Using rest api of azure devops
Using rest api of azure devops

Time:03-24

I want to fetch data from the rest api of Azure Devops using Java.But not sure how to establish the connection.May be personal acces token will help,but how to use the token in Code for establishing the connection between code and azure devops? An example from anyone will be very helpful.

A code example will be very helpfull

CodePudding user response:

If I am understanding you correctly, you are trying to call azure APIs, and those API need authorization token?

For example this azure API to send data into Azure queue : https://docs.microsoft.com/en-us/rest/api/servicebus/send-message-to-queue

It needs some payload and Authorization in request header !!


If my Understanding is correct, than from java you need to use any rest client or HTTP client to call the REST API and you need to pass the Authorization token in the request header

For calling a Rest API in java with passing header below is an example:

MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("Authorization", "Bearer <Azure AD JWT token>"); // set your token here

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON); //someother http headers you want to set

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

RestTemplate restTemplate = new RestTemplate();
String azure_url = "https://azure_url"; // your azure devops REST URL

ResponseEntity<String> response = restTemplate.postForEntity(azure_url, request , String.class);

CodePudding user response:

A small example with httpclient:

static String ServiceUrl = "https://dev.azure.com/<your_org>/";
static String TeamProjectName = "your_team_project_name";
static String UrlEndGetWorkItemById = "/_apis/wit/workitems/";
static Integer WorkItemId = 1208;
static String PAT = "your_pat";

String AuthStr = ":"   PAT;
Base64 base64 = new Base64();
        
String encodedPAT = new String(base64.encode(AuthStr.getBytes()));
        
URL url = new URL(ServiceUrl   TeamProjectName   UrlEndGetWorkItemById   WorkItemId.toString());
HttpURLConnection con = (HttpURLConnection) url.openConnection();
        
con.setRequestProperty("Authorization", "Basic "   encodedPAT);
con.setRequestMethod("GET");
        
int status = con.getResponseCode();

Link to the file: ResApiMain.java

  • Related