python代码的订阅密钥无效,但是相同的密钥在westus.dev.cognitive.microsoft.com上正常工作

时间:2017-02-09 16:08:08

标签: python microsoft-cognitive

我刚刚开始使用microsoft的计算机视觉OCR api,订阅密钥和图像网址在https://westus.dev.cognitive.microsoft.com/docs/services/56f91f2d778daf23d8ec6739/operations/56f91f2e778daf14a499e1fc/console上工作正常

但是在使用python代码时出现以下错误

{“statusCode”:401,“message”:“由于订阅密钥无效而拒绝访问。确保为有效订阅提供有效密钥。”}

我尽力弄清楚错误但失败了。

我做错了什么?

提前致谢。

import httplib, urllib, base64

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': '{1111460aa78d4b27****************}',
}

params = urllib.urlencode({
    # Request parameters
    'language': 'unk',
    'detectOrientation ': 'true',
})

try:
    conn = httplib.HTTPSConnection('westus.api.cognitive.microsoft.com')
    conn.request("POST", "/vision/v1.0/ocr?%s" % params, "{\"url\":\"https://s-media-cache-ak0.pinimg.com/originals/fb/e6/56/fbe65691cb66c6f035a859d9671c3fe5.jpg\"}", headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

1 个答案:

答案 0 :(得分:1)

您需要删除API密钥值的花括号,即:

public class PermissionsUtils {

public static final int REQUEST_PERMISSION_MULTIPLE = 0;
public static final int REQUEST_PERMISSION_CAMERA = 1;
public static final int REQUEST_PERMISSION_LOCATION = 2;
public static final int REQUEST_WRITE_EXTERNAL = 3;

public static boolean checkAndRequestPermissions(Activity activity) {
    System.out.println("PermissionsUtils checkAndRequestPermissions()");

    int permissionCamera = ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
    int permissionLocation = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION);
    int permissionWriteExternal = ContextCompat.checkSelfPermission(activity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);

    // Permission List
    List<String> listPermissionsNeeded = new ArrayList<>();

    // Camera Permission
    if (permissionCamera != PackageManager.PERMISSION_GRANTED) {
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)) {
            Toast.makeText(activity, "Camera Permission is required for this app to run", Toast.LENGTH_SHORT)
                    .show();
        }
        listPermissionsNeeded.add(Manifest.permission.CAMERA);
    }

    // Read/Write Permission
    if (permissionWriteExternal != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    // Location Permission
    if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
    }

    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions(activity,
                listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
                REQUEST_PERMISSION_MULTIPLE);
        return false;
    }

    return true;
}

/**
 * Requests the Camera permission. If the permission has been denied
 * previously, a SnackBar will prompt the user to grant the permission,
 * otherwise it is requested directly.
 */
public static void requestCameraPermission(Activity activity) {
    // Here, thisActivity is the current activity
    // System.out.println("requestCameraPermission() INITIAL");
    // Toast.makeText(this, "requestCameraPermission() INITIAL",
    // Toast.LENGTH_LONG).show();
    if (ContextCompat.checkSelfPermission(activity,
            Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)) {
            // Toast.makeText(activity, "Camera permission is
            // needed for this app to run ",
            // Toast.LENGTH_SHORT).show();
            // System.out.println("requestCameraPermission() SHOW INFO");

            // Show an explanation to the user *asynchronously* -- don't
            // block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
            ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.CAMERA },
                    REQUEST_PERMISSION_CAMERA);

        } else {
            // No explanation needed, we can request the permission.
            // System.out.println("requestCameraPermission() ASK
            // PERMISSION");

            ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.CAMERA },
                    REQUEST_PERMISSION_CAMERA);
        }
        // Permission is granted
    } else {
        System.out.println("requestCameraPermission() PERMISSION ALREADY GRANTED");

    }

}

public static void requestLocationPermission(Activity activity) {
    if (ContextCompat.checkSelfPermission(activity,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            Toast.makeText(activity, "LOCATION permission is needed to display location info ", Toast.LENGTH_SHORT)
                    .show();
            // Show an explanation to the user *asynchronously* -- don't
            // block this thread waiting for the user's response! After the
            // user sees the explanation, try again to request the
            // permission.
            ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    REQUEST_PERMISSION_LOCATION);

            Toast.makeText(activity, "REQUEST LOCATION PERMISSION", Toast.LENGTH_LONG).show();

        } else {
            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    REQUEST_PERMISSION_LOCATION);
            Toast.makeText(activity, "REQUEST LOCATION PERMISSION", Toast.LENGTH_LONG).show();
            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
        // Permission is granted
    } else {

    }
}

public static void requestWriteExternalPermission(Activity activity) {
    if (ContextCompat.checkSelfPermission(activity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Toast.makeText(activity, "Write permission is needed to create Excel file ", Toast.LENGTH_SHORT).show();
            // Show an explanation to the user *asynchronously* -- don't
            // block this thread waiting for the user's response! After the
            // user sees the explanation, try again to request the
            // permission.
            ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    REQUEST_WRITE_EXTERNAL);

            Toast.makeText(activity, "REQUEST LOCATION PERMISSION", Toast.LENGTH_LONG).show();

        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    REQUEST_WRITE_EXTERNAL);

        }
    }
}

public static boolean hasPermissions(Context context, String... permissions) {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}