Authorization issue when performing patch request using apach http client

Viewed 24

I am trying to update work item in azure using apache http client in java but getting error response

{"$id":"1","innerException":null,"message":"TF400813: The user 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' is not authorized to access this resource.","typeName":"Microsoft.TeamFoundation.Framework.Server.UnauthorizedRequestException, Microsoft.TeamFoundation.Framework.Server","typeKey":"UnauthorizedRequestException","errorCode":0,"eventId":3000}

Below is my code

import java.io.IOException;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class testee {
     public static void main(String[] args) {

            try {
            String url = "https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{id}?api-version=7.1-preview.3";

                String result = sendPatch(url);
                System.out.println(result);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        private static String sendPatch(String url) throws IOException {
            
            String result = "";
            HttpPatch patch = new HttpPatch(url);
            patch.addHeader("content-type", "application/json-patch+json");
            patch.addHeader("X-Auth-Email", "{email}");
            patch.addHeader("X-Auth-Key", "{personal access token}");
            String jsonString = "[{\"op\":\"replace\",\"path\":\"/fields/System.Title\",\"value\":\"Custom Message\"},{\"op\":\"add\",\"path\":\"/fields/System.State\",\"value\":\"Active\"}]";

            // send a JSON data
            ((HttpPatch)patch).setEntity(new StringEntity(jsonString));

            try (CloseableHttpClient httpClient = HttpClients.createDefault();
                 CloseableHttpResponse response = httpClient.execute(patch)) {

                result = EntityUtils.toString(response.getEntity());
            }

            return result;
        }

}
0 Answers
Related