0
votes

I'm trying to change (update) Visual Studio Online work item (of type User Story) using REST API (https://www.visualstudio.com/en-us/docs/integrate/api/wit/work-items#update-work-items)

private static String addCommenttoStackOverflow() throws IOException {
    String url = "https://<myproject>.visualstudio.com/DefaultCollection/_apis/wit/workitems/<specific id>?api-versoin=1.0";
    HttpUriRequest request = RequestBuilder.patch(url)
            .setHeader(HttpHeaders.CONTENT_TYPE, "application/json-patch+json")
            .setHeader("Authorization", "Basic " + getVsoAuthenticationString())
            .setEntity(EntityBuilder.create()
                    .setContentEncoding("UTF8")
                    .setText("[{\"op\":\"add\",\"path\":\"/fields/System.History\",\"value\":\"JavaScript implementation for Microsoft Account\"}]")
                    .build())
            .build();


    try(CloseableHttpClient httpclient = HttpClients.createDefault()) {
        try(CloseableHttpResponse response = httpclient.execute(request)) {

            System.out.println("Status = " + response.getStatusLine());
            HttpEntity entity =response.getEntity();
            System.out.println(entity.toString());
            System.out.println(entity.getContent().toString());
            ResponseHandler<String> handler = new BasicResponseHandler();
            return handler.handleResponse(response);
        }
    }
}

I'm using Apache HttpComponents for Java REST client and basic basic authentication (PAT). I'd successfully used very similar code for querying, but unable to update.

1

1 Answers

0
votes

Refer to this code below:

byte[] encodedBytes = Base64.getEncoder().encode("test:{your personal access token}".getBytes());
            String basedToken=new String(encodedBytes);
            HttpClient httpClient = HttpClientBuilder.create().build();

            HttpPatch patchRequest=new HttpPatch("https://{account}.visualstudio.com/DefaultCollection/_apis/wit/workitems/{work item id}?api-version=1.0");
            StringEntity input = new StringEntity("[{\"op\":\"add\",\"path\":\"/fields/System.History\",\"value\":\"JavaScript implementation for Microsoft Account2\"}]");
            input.setContentType("application/json-patch+json");
            patchRequest.setEntity(input);
            patchRequest.setHeader("Authorization", "Basic "+basedToken);

            HttpResponse response = httpClient.execute(patchRequest);



            BufferedReader br = new BufferedReader(
                            new InputStreamReader((response.getEntity().getContent())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }