Azure Devops Java HttpsURLConnection authentication

Steve 1 Reputation point
2022-08-16T14:30:31.133+00:00

HttpsURLConnection problem, getting a 401 error when running an ADO API to create a new work item. It works from curl command line, but not in Java. Is there something different I need to do in Java? Can I not use an http url connection for some reason?

I have tried various suggestions and alternatives I have found, but so far no luck. I am using a PAT generated from ADO for password, so not sure if that is related to the problem. I tried revoking the PAT and regenerate, but it did not help. Can someone tell me what I am doing wrong here?

This works:

  curl -u me:myPAT  -x myproxy.corp:80 \  
  'https://dev.azure.com/mycompany/_apis/wit/workitems/$Bug?api-version=6.0' \  
  -H 'Content-Type: application/json-patch+json' \  
  --data-binary '[{"op":"add","path":"/fields/System.Title","value":"Test API"}]'  

This does not:

    public static void createIncident() {  
  
    String input = "[{\"op\":\"add\",\"path\":\"/fields/System.Title\",\"value\":\"Test API\"}]";  
    String userpass="me:myPAT";  
    String basicAuth = "Basic :" + new String(Base64.getEncoder().encode(userpass.getBytes()));  
    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("myproxy.corp", 80));  
  
    try {  
        URL url = new URL("https://dev.azure.com/mycompany/_apis/wit/workitems/$Bug?api-version=6.0");  
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(proxy);  
        conn.setRequestProperty("Authorization", basicAuth);  
        conn.setRequestProperty("Accept", "application/json-patch+json");  
        conn.setRequestProperty("Content-Type", "application/json-patch+json");  
        conn.setDoOutput(true);  
        conn.setRequestMethod("POST");  
  
        OutputStream os = conn.getOutputStream();  
        os.write(input.getBytes());  
        os.flush();  
        if (conn.getResponseCode() != HttpsURLConnection.HTTP_CREATED) {  
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());  
        }  
        conn.disconnect();  
    } catch (MalformedURLException e) {  
        e.printStackTrace();  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  
}  
Not Monitored
Not Monitored
Tag not monitored by Microsoft.
35,962 questions
0 comments No comments
{count} votes