javaazureazure-api-managementbing-api

Bing Search API: Getting 401 Acces Denied error while using the right suscription key


I'm trying to connect to the Bing Search API in Java.

However, calling connection.getInputStream(), it throws an HTTP 401 error.

The same error occurs even when I intentionally use an incorrect subscription key. I'm certain that my actual subscription key is correct.

Any ideas on why this might be happening?


Solution

  • I got the same error while tried to call Bing web search API. I solved this issue by creating a cognitive service instance and use its endpoint and key:

    enter image description here

    This is my test code based on yours:

    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLEncoder;
    
    import javax.net.ssl.HttpsURLConnection;
    
    public class HTTPtest {
    
        public static void main(String[] args) {
            String Endpoint = "<Endpoint>";
            String key = "<key>";
    
            String input = "Bill Gates divorce";
    
            try {
                URL url = new URL(Endpoint + "bing/v7.0/search" + "?q=" + URLEncoder.encode(input, "UTF-8"));
    
                HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
                connection.setRequestProperty("Ocp-Apim-Subscription-Key", key);
    
                InputStream stream = connection.getInputStream();
    
                System.out.println(new String(stream.readAllBytes()));
    
            } catch (Exception e) {
    
                System.out.println(e.getMessage());
    
            }
        }
    }
    

    Result:

    enter image description here

    Let me know if you have any more questions.