0

I need to connect VSTS Server using rest API in java. i have been through the documentation provided by Microsoft, but its for c# i need sample java programme for java, is there any jar released by Microsoft for VSTS, as i cannot find any jar related to this. Using c# i am able to connect with Vsts but i want some sample code for java.

sample code i have used in c# is :

public static async void GetProjects()
{
try
{
    var personalaccesstoken = "PAT_FROM_WEBSITE";

    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.Accept.Add(
            new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
            Convert.ToBase64String(
                System.Text.ASCIIEncoding.ASCII.GetBytes(
                    string.Format("{0}:{1}", "", personalaccesstoken))));

        using (HttpResponseMessage response = await client.GetAsync(
                    "https://dev.azure.com/{organization}/_apis/projects"))
        {
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}
}
  • 1
    Stack Overflow is not a service that writes code for you in your language of choice. – Daniel Mann Mar 07 '19 at 13:28
  • daniel I have already provided code in the previous post, I have used in java to connect but getting connection refused – Rajesh Bhardwaj Mar 07 '19 at 14:33
  • 2
    @RajeshBhardwaj if you have a code sample you have tried then you should add it to your question, as well as an extract of the stack trace with the exact error you're facing. Then you will have higher chances of receiving a quality response – Nicolás Carrasco-Stevenson Mar 07 '19 at 15:13

1 Answers1

1

This is my first java experience ))

Try that to get work item:

package com.restapi.sample;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Scanner;

import org.apache.commons.codec.binary.Base64;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class ResApiMain {

    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";

    public static void main(String[] args) {

        try {

            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);
            System.out.println("URL - " + url.toString());
            System.out.println("PAT - " + encodedPAT);
            con.setRequestMethod("GET");

            int status = con.getResponseCode();

            if (status == 200){
                String responseBody;
                try (Scanner scanner = new Scanner(con.getInputStream())) {
                    responseBody = scanner.useDelimiter("\\A").next();
                    System.out.println(responseBody);
                }

                try {
                    Object obj = new JSONParser().parse(responseBody);
                    JSONObject jo = (JSONObject) obj;

                    String WIID = (String) jo.get("id").toString();
                    Map<String, String> fields = (Map<String, String>) jo.get("fields");
                    System.out.println("WorkItemId - " + WIID);
                    System.out.println("WorkItemTitle - " + fields.get("System.Title"));
                } catch (ParseException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }           

            con.disconnect();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

Additional jars:

  1. to work with json http://www.java2s.com/Code/Jar/j/Downloadjsonsimple111jar.htm
  2. to encode with base64: http://commons.apache.org/proper/commons-codec/download_codec.cgi

Samples to work with requests:

  1. https://www.baeldung.com/java-http-request
  2. How to use java.net.URLConnection to fire and handle HTTP requests

Check the url generated in the eclipse console: enter image description here

Shamrai Aleksander
  • 7,096
  • 2
  • 9
  • 17
  • I`ve exported this project (eclipse neon 4.6.3) to github: https://github.com/ashamrai/AzureDevOpsExtensions/tree/master/AzureDevOpsRestApiJavaExample – Shamrai Aleksander Mar 07 '19 at 16:08
  • Hi @shamrai i have tried with the code you have provide and getting error: java.net.ConnectException: Connection timed out: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source) – Rajesh Bhardwaj Mar 08 '19 at 06:27
  • 1
    That example works in my vm. @RajeshBhardwaj try to past the generated url to a browser. Or maybe some proxy exists in your network. – Shamrai Aleksander Mar 10 '19 at 10:20
  • 1
    thanks buddy actually i have already a code that i use to connect with the local tfs but getting error of connection timeout when tried with azure tfs, i have finally solved the issue. The issue was mainly in token generation setting – Rajesh Bhardwaj Mar 10 '19 at 17:57
  • using your code once i tried to do get a woritems i m getting error of 400 – Rajesh Bhardwaj Mar 18 '19 at 06:58
  • I used this code and get succesfull 200 I only i recommend to check and fill all the url requierements to make it work – M.Parra May 12 '20 at 21:19