Android 如何调用腾讯OCR通用印刷体API

我尝试在Android上调用腾讯OCR通用印刷体API(https://cloud.tencent.com/doc...

鉴权签名如下:

package com.hsare.tools;






import android.annotation.TargetApi;
import android.os.Build;
import android.util.Base64;


import java.util.Random;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class Sign {

    /**
     * 生成 Authorization 签名字段
     *
     * @param appId
     * @param secretId
     * @param secretKey
     * @param bucketName
     * @param expired
     * @return
     * @throws Exception
     */
    public static String appSign(long appId, String secretId, String secretKey, String bucketName,
                                 long expired) throws Exception {
        long now = System.currentTimeMillis() / 1000;
        int rdm = Math.abs(new Random().nextInt());
        String plainText = String.format("a=%d&b=%s&k=%s&e=%d&t=%d&r=%d", appId, bucketName,
                secretId, now, now + expired, rdm);
        byte[] hmacDigest = HmacSha1(plainText, secretKey);
        byte[] signContent = new byte[hmacDigest.length + plainText.getBytes().length];
        System.arraycopy(hmacDigest, 0, signContent, 0, hmacDigest.length);
        System.arraycopy(plainText.getBytes(), 0, signContent, hmacDigest.length,
                plainText.getBytes().length);
        return Base64Encode(signContent);
    }

    /**
     * 生成 base64 编码
     *
     * @param binaryData
     * @return
     */

    @TargetApi(Build.VERSION_CODES.O)
    public static String Base64Encode(byte[] binaryData) {
        String encodedstr = Base64.encodeToString(binaryData, Base64.NO_WRAP);//解
        return encodedstr;
    }

    /**
     * 生成 hmacsha1 签名
     *
     * @param binaryData
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] HmacSha1(byte[] binaryData, String key) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        mac.init(secretKey);
        byte[] HmacSha1Digest = mac.doFinal(binaryData);
        return HmacSha1Digest;
    }

    /**
     * 生成 hmacsha1 签名
     *
     * @param plainText
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] HmacSha1(String plainText, String key) throws Exception {
        return HmacSha1(plainText.getBytes(), key);
    }
}

post请求代码如下:

package com.hsare.ocrtest;


import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.hsare.tools.Config;
import com.hsare.tools.Sign;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;

import okhttp3.OkHttpClient;
import okhttp3.Request;

import okhttp3.Response;



public class MainActivity extends AppCompatActivity {

    private static final String TAG = "SSSSSSSSSSSSSS:";
    private String sign = "";
    private String url1 = "https://recognition.image.myqcloud.com/ocr/general";
    private String url2 = "https://www.yanshishuo.com/wp-content/uploads/2017/09/gao.jpg";
    OkHttpClient client = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    

    //post 请求
    public void doPost(View view) {

        OkHttpClient client = new OkHttpClient();

        try {
            //鉴权签名
            sign = Sign.appSign(Config.APPID, Config.SECRETID, Config.SECRETKEY, "sd", 1);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //请求参数
        FormBody formBody = new FormBody.Builder()
                .add("appid", "1251169844")
                .add("url",url2)
                .build();

        Log.e(TAG, "sign: "+sign );

        //请求头
        Request request = new Request.Builder()
                .post(formBody)
                .url(url2)
                .addHeader("host","recognition.image.myqcloud.com")
                .addHeader("content-type","application/json")
                .addHeader("authorization",sign)
                .build();


            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "onFailure: ", e);
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    new Thread() {
                        @Override
                        public void run() {

                            Looper.prepare();
                            Log.e(TAG, "response: "+response );
                            Looper.loop();
                        }
                    }.start();
                }
            });




    }

}


Config的设置:

package com.hsare.tools;

public class Config {

    public static final long APPID = 1251169844;
    public static final String SECRETID = "AKIDkNo6D8nSxIRPBloLOHzVs43pOlwvxS8d";
    public static final String SECRETKEY = "TnvrbCbopfJkz0pTvDLK9nIbidP1Qjpb";




}

但是返回的结果是这个:response: Response{protocol=h2, code=405, message=, url=https://www.yanshishuo.com/wp-content/uploads/2017/09/gao.jpg}

我哪里弄错了?有老铁帮下忙吗?

阅读 4.9k
1 个回答

自己捣鼓出来了...
签名部分:

主要是腾讯那边给出的拼接是:

String.format("a=%d&b=%s&k=%s&t=%d&e=%d&r=%d", appId, bucketName,
                secretId, now, now + expired, rdm);

其中a=%d

把它改成a=%s就可以了。。。

String.format("a=%s&k=%s&e=%d&t=%d&r=%d", appId, secretId, now + 2592000, now, rdm);

部分代码:

            //请求头
            String json = jsonObject.put("appid", Config.APPID)
                                    .put("url", Config.image_url).toString();
            //鉴权签名
            sign = Sign.appSign(Config.APPID, Config.SECRETID, Config.SECRETKEY);
            Log.e(TAG, "Sign:" + sign);

            RequestBody body = RequestBody.create(JSON, json);


            //请求体
            final Request request = new Request.Builder()
                    .header("Host", "recognition.image.myqcloud.com")
                    .header("Content-Type", "application/json")
                    .header("Authorization", sign)
                    .post(body)
                    .url(Config.code_url)
                    .build();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题