初级篇,利用 Android 搭建一个简易的文字识别APP-印刷体高精度版本

2023-12-21 07:55:18 浏览数 (3)

初始,准备工作

  • 安装Android sudio 开发工具
  • 搭建android 运行环境(java14)
  • 腾讯云OCR产品开通,及其秘钥获取

效果展示图

使用效果展示图使用效果展示图

一、新建空项目

新建空项目新建空项目
项目基础信息项目基础信息
空项目结构空项目结构

二、构建前端界面

初始界面初始界面
实际界面效果展示实际界面效果展示

前端activity_main.xml 布局代码展示 (LinearLayout 线性布局)

前端学习参考:https://www.runoob.com/w3cnote/android-tutorial-linearlayout.html

代码语言:javascript复制
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="#CC0000"
        android:paddingLeft="56dp"
        android:paddingRight="56dp">
        <TextView
            android:id="@ id/nav_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="文字识别"
            android:textColor="#FDFDFD"
            android:textSize="16sp" />
    </FrameLayout>
    <ImageView
        android:id="@ id/photoView"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:layout_margin="20dp"
        />
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="44dp"
        android:orientation="horizontal"
        android:layout_gravity="center_vertical"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:layout_marginTop="10dp">

        <Button
            android:id="@ id/albumBtnEvt"
            android:layout_width="wrap_content"
            android:layout_height="44dp"
            android:background="#FF5722"
            android:text="打 开 相 册"
            android:textColor="#FFFEFE"
            android:onClick="getImageFromAlbum"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="44dp"
            android:background="#FF5722"
            android:text="拍 照"
            android:textColor="#FFFEFE"
            android:layout_marginLeft="20dp"
            android:onClick="toCamera"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:background="#A52A2A"
            android:text="发 送 请 求"
            android:textColor="#FFFEFE"
            android:layout_marginLeft="20dp"
            android:onClick="onFormBtnClick"/>
            
    </LinearLayout>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:orientation="horizontal"
        android:layout_gravity="center_vertical"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:layout_marginTop="50dp">
        <!--android:layout_gravity="center_vertical"-->

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@null"
            android:text="内 容"
            android:paddingLeft="12dp"
            android:paddingRight="12dp"
            android:textSize="18dp"
            android:focusable="false"/>

        <EditText
            android:id="@ id/number"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:background="@null"
            android:paddingLeft="12dp"
            android:paddingRight="12dp"
            android:textSize="18dp"
            android:focusable="false"/>
    </LinearLayout>

</LinearLayout>

二、实现后端交互 MainActivity.java

(1)更改继承类,指向Activity,构建初始方法,实例化前端控件

代码语言:javascript复制
package com.example.ocrdemo;

import android.app.Activity;
import android.os.Bundle;

//改变继承类
public class MainActivity extends Activity {

    //申明前端布局属性
    private TextView numberEvt;
    //申明前端图片展示属性
    private ImageView photoViewEvt;

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

    private void init(){
        //android 7.0系统解决拍照的问题
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        //初始化控件 findViewById 用R.id到前端通过android:id指定的id 获取当前选中属性
        photoViewEvt    =     findViewById(R.id.photoView);
        numberEvt       =     findViewById(R.id.number);
    }
}

(2)相机及其相册控制

代码语言:javascript复制
    //设置需要的拍照、相册权限
    private static String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA };//权限
    /**
     * 获取相册事件
     * @param v
     */
    public void getImageFromAlbum(View v) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 100);// 100: 相册的返回码参数(随便一个值就行,只要不冲突就好)
    }

    /**
     * 跳转相机
     * @param v
     */
    public void toCamera(View v) {
        //查看相机权限 用户手动授权
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)  != PackageManager.PERMISSION_GRANTED ){
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, 3);
        }else{
            //已经有权限
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  //跳转到 ACTION_IMAGE_CAPTURE
            //判断内存卡是否可用,可用的话就进行存储
            //putExtra:取值,Uri.fromFile:传一个拍照所得到的文件,fileImg.jpg:文件名
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES),"fileImg.jpg")));
            startActivityForResult(intent,101); // 101: 相机的返回码参数(随便一个值就行,只要不冲突就好)
        }
    }    

相册绑定示如下

前端给(打开相册、拍照按钮)绑定事件,通过android:onClick 指定方法,上述前端代码已绑定,

代码语言:javascript复制
 <Button
            android:id="@ id/albumBtnEvt"
            android:layout_width="wrap_content"
            android:layout_height="44dp"
            android:background="#FF5722"
            android:text="打 开 相 册"
            android:textColor="#FFFEFE"
            android:onClick="getImageFromAlbum"/>

相册及拍照后确定后图像处理操作事件方法设置

代码语言:javascript复制
   /**
     * 自带方法,相册更相机时间确定后,返回回来指定的方法
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        switch (requestCode){
            case 100:   //相册返回的数据(相册的返回码)
                if (data == null) {
                    Log.e("onActivityResult", "暂无内容");
                    return;
                }
                Uri uriPath = data.getData();
                try {
                    //获取相册的图片bitmap值
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uriPath));
                    //质量压缩
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                    byte[] bytes = bos.toByteArray();
                    Bitmap mSrcBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                    photoViewEvt.setImageBitmap(mSrcBitmap);
                } catch (IOException e) {
                    Log.e("onActivityResult 100",  e.getMessage());
                    e.printStackTrace();
                }
                break;
            case 101:  //相机返回的数据(相机的返回码)
                try {
                    File tempFile = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES),"fileImg.jpg");  //相机取图片数据文件
                    Uri uri = Uri.fromFile(tempFile);   //图片文件
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                    //质量压缩
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                    byte[] bytes = bos.toByteArray();
                    Bitmap mSrcBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                    photoViewEvt.setImageBitmap(mSrcBitmap);
                } catch (IOException e) {
                    Log.e("onActivityResult", e.getMessage());
                    e.printStackTrace();
                }
                break;
        }
    }

三、接口数据获取及请求腾讯云OCR API ,解析数据部署到前端(前端按钮绑定此事件,参考相册绑定,前端展示代码已绑定)

代码语言:javascript复制
   /**
     * 表单提交点击事件
     * 前端通过android:onClick 指定点击时间触发方法
     * @param v
     */
    public void onFormBtnClick(View v){
        //android4.0 以后不能在主线程发起网络请求,该异步网络请求
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                //获取前端相册或者拍照时间生成的缩略图的Bitmap值
                Bitmap photoBitmap = ((BitmapDrawable) photoViewEvt.getDrawable()).getBitmap();
                //图片Bitmap -转化-> base64
                String photoBase64 = bitmapToBase64(photoBitmap);

                Map<String, Object> params = new HashMap<>();
                params.put("ImageBase64", photoBase64);
                Gson gson = new Gson();
                String param = gson.toJson(params);
                Log.e("request", param);
                // TODO Auto-generated method stub

                //发送请求 本地封装的https 请求
                response = TencentOcrAuth.getOcrAuthTC3("GeneralAccurateOCR", param, "ap-beijing",TencentOcrAuth.Version);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //处理json 数据 把JSON数据转化为对象
                            JSONObject jsonObject = new JSONObject(response.toString());
                            //返回错误提示
                            if (jsonObject.getJSONObject("Response").has("Error")){
                                String Message = jsonObject.getJSONObject("Response").getJSONObject("Error").getString("Message");
                                String RequestId = jsonObject.getJSONObject("Response").getString("RequestId");
                                String Code = jsonObject.getJSONObject("Response").getJSONObject("Error").getString("Code");
                                //给前端设置值
                                numberEvt.setText(Message);
                            } else {
                                //正确反馈处理结果
                                String data= jsonObject.getJSONObject("Response")
                                //String contentA = jsonObject.getJSONObject("Response").getJSONArray("TextDetections").getJSONObject(0).getString("DetectedText");
                                //JSONArray ocrCon = jsonObject.getJSONObject("Response").getJSONArray("TextDetections");
                                //String content = "";
                                //for(int i=0; i < ocrCon.length(); i  ){
                                    //3、把里面的对象转化为JSONObject
                                    //JSONObject ocrContent = ocrCon.getJSONObject(i);
                                    //拼接
                                    //content  = ocrContent.getString("DetectedText");
                                //}
                                //给前端设置值
                                //numberEvt.setText(content);
                            }
                        }catch (JSONException e){
                            Log.e("JSON error", e.getMessage());
                        }
                    }
                });
            }
        }).start();
    }

四、权限赋予 (src > main > AndroidManifest.xml)

代码语言:javascript复制
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ocrdemo">

    <!--网络权限-->
    <uses-permission android:name="android.permission.INTERNET" />
    <!--相册及拍照权限-->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="com.miui.whetstone.permission.ACCESS_PROVIDER"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

附加代码

OCR通用文字识别响应示例

代码语言:javascript复制
{
    "Response": {
        "Angle": 359.989990234375,
        "RequestId": "05441696-96fb-48a8-a445-49df03836fba",
        "TextDetections": [
            {
                "AdvancedInfo": "{"Parag":{"ParagNo":1}}",
                "Confidence": 99,
                "DetectedText": "轻断食:正在横扫全球的瘦身革命",
                "ItemPolygon": {
                    "Height": 22,
                    "Width": 263,
                    "X": 446,
                    "Y": 93
                },
                "Polygon": [
                    {
                        "X": 446,
                        "Y": 93
                    },
                    {
                        "X": 709,
                        "Y": 96
                    },
                    {
                        "X": 708,
                        "Y": 118
                    },
                    {
                        "X": 446,
                        "Y": 114
                    }
                ],
                "WordCoordPoint": [],
                "Words": []
            },
            {
                "AdvancedInfo": "{"Parag":{"ParagNo":2}}",
                "Confidence": 99,
                "DetectedText": "专题报道。",
                "ItemPolygon": {
                    "Height": 25,
                    "Width": 100,
                    "X": 47,
                    "Y": 201
                },
                "Polygon": [
                    {
                        "X": 47,
                        "Y": 201
                    },
                    {
                        "X": 147,
                        "Y": 200
                    },
                    {
                        "X": 147,
                        "Y": 225
                    },
                    {
                        "X": 48,
                        "Y": 226
                    }
                ],
                "WordCoordPoint": [],
                "Words": []
            },
            {
                "AdvancedInfo": "{"Parag":{"ParagNo":3}}",
                "Confidence": 99,
                "DetectedText": "2009年,我写了 《减肥前要做的101件事》(101 Things to Do",
                "ItemPolygon": {
                    "Height": 27,
                    "Width": 628,
                    "X": 88,
                    "Y": 244
                },
                "Polygon": [
                    {
                        "X": 88,
                        "Y": 244
                    },
                    {
                        "X": 716,
                        "Y": 247
                    },
                    {
                        "X": 716,
                        "Y": 274
                    },
                    {
                        "X": 88,
                        "Y": 271
                    }
                ],
                "WordCoordPoint": [],
                "Words": []
            },
            {
                "AdvancedInfo": "{"Parag":{"ParagNo":3}}",
                "Confidence": 99,
                "DetectedText": "Before You Diet), 归纳我尝试各种流行减肥法的气馁经验, 每种方",
                "ItemPolygon": {
                    "Height": 27,
                    "Width": 675,
                    "X": 42,
                    "Y": 292
                },
                "Polygon": [
                    {
                        "X": 42,
                        "Y": 292
                    },
                    {
                        "X": 717,
                        "Y": 290
                    },
                    {
                        "X": 717,
                        "Y": 317
                    },
                    {
                        "X": 43,
                        "Y": 320
                    }
                ],
                "WordCoordPoint": [],
                "Words": []
            },
            {
                "AdvancedInfo": "{"Parag":{"ParagNo":3}}",
                "Confidence": 99,
                "DetectedText": "法似乎都注定失败。",
                "ItemPolygon": {
                    "Height": 25,
                    "Width": 192,
                    "X": 45,
                    "Y": 340
                },
                "Polygon": [
                    {
                        "X": 45,
                        "Y": 340
                    },
                    {
                        "X": 237,
                        "Y": 340
                    },
                    {
                        "X": 237,
                        "Y": 365
                    },
                    {
                        "X": 45,
                        "Y": 365
                    }
                ],
                "WordCoordPoint": [],
                "Words": []
            },
            {
                "AdvancedInfo": "{"Parag":{"ParagNo":4}}",
                "Confidence": 99,
                "DetectedText": "这二十年来我接触过的减肥方法中, 只有轻断食让我在瘦下来之 ",
                "ItemPolygon": {
                    "Height": 27,
                    "Width": 633,
                    "X": 88,
                    "Y": 384
                },
                "Polygon": [
                    {
                        "X": 88,
                        "Y": 384
                    },
                    {
                        "X": 721,
                        "Y": 384
                    },
                    {
                        "X": 721,
                        "Y": 411
                    },
                    {
                        "X": 88,
                        "Y": 411
                    }
                ],
                "WordCoordPoint": [],
                "Words": []
            },
            {
                "AdvancedInfo": "{"Parag":{"ParagNo":4}}",
                "Confidence": 99,
                "DetectedText": "后不反弹。",
                "ItemPolygon": {
                    "Height": 24,
                    "Width": 105,
                    "X": 42,
                    "Y": 435
                },
                "Polygon": [
                    {
                        "X": 42,
                        "Y": 435
                    },
                    {
                        "X": 147,
                        "Y": 433
                    },
                    {
                        "X": 148,
                        "Y": 457
                    },
                    {
                        "X": 43,
                        "Y": 460
                    }
                ],
                "WordCoordPoint": [],
                "Words": []
            },
            {
                "AdvancedInfo": "{"Parag":{"ParagNo":4}}",
                "Confidence": 96,
                "DetectedText": "至于抗衰老的健康益处,",
                "ItemPolygon": {
                    "Height": 24,
                    "Width": 250,
                    "X": 148,
                    "Y": 433
                },
                "Polygon": [
                    {
                        "X": 148,
                        "Y": 433
                    },
                    {
                        "X": 398,
                        "Y": 433
                    },
                    {
                        "X": 398,
                        "Y": 457
                    },
                    {
                        "X": 148,
                        "Y": 457
                    }
                ],
                "WordCoordPoint": [],
                "Words": []
            },
            {
                "AdvancedInfo": "{"Parag":{"ParagNo":4}}",
                "Confidence": 99,
                "DetectedText": "更是得来全不费工夫。",
                "ItemPolygon": {
                    "Height": 26,
                    "Width": 223,
                    "X": 398,
                    "Y": 431
                },
                "Polygon": [
                    {
                        "X": 398,
                        "Y": 431
                    },
                    {
                        "X": 621,
                        "Y": 431
                    },
                    {
                        "X": 621,
                        "Y": 457
                    },
                    {
                        "X": 398,
                        "Y": 457
                    }
                ],
                "WordCoordPoint": [],
                "Words": []
            }
        ]
    }
}

bitmap 转化 base64 方法

代码语言:javascript复制
    /*
     * bitmap转base64
     * */
    private static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

新建Tencent OCR鉴权及其请求类(src > main > com.xxx > TencentOcrAuth.java

代码语言:javascript复制
package com.example.tencentocr;

import android.text.TextUtils;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

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

public class TencentOcrAuth {

    private static String SecretId  = "";
    private static String SecretKey = "";

    private static String Url       = "https://ocr.tencentcloudapi.com";
    //规范请求串
    private static String  HTTPRequestMethod     = "POST";
    private static String  CanonicalURI          = "/";
    private static String  CanonicalQueryString  = "";
    private static String  CanonicalHeaders      = "content-type:application/json; charset=utf-8nhost:ocr.tencentcloudapi.comn";
    private static String  SignedHeaders         = "content-type;host";//参与签名的头部信息

    //签名字符串
    private static String  Algorithm             = "TC3-HMAC-SHA256";
    private static String  Service               = "ocr";
    private static String  Stop                  = "tc3_request";

    //版本
    public static String  Version               = "2018-11-19";

    /**
     * v3鉴权
     * @param action  人脸识别接口名 例如 DetectFace
     * @param paramJson json化的参数
     * @param region    地区
     * @param version  版本号 2018-11-19
     * @return
     */
    public static String getOcrAuthTC3(String action, String paramJson, String region, String version){
        try{
            String hashedRequestPayload   =   HashEncryption(paramJson);
            String CanonicalRequest =
                    HTTPRequestMethod   'n'  
                            CanonicalURI   'n'  
                            CanonicalQueryString   'n'  
                            CanonicalHeaders   'n'  
                            SignedHeaders   'n'  
                            hashedRequestPayload;
            //时间戳
            Date date = new Date();
            //微秒->秒
            String timestamp    =   String.valueOf(date.getTime() / 1000);

            //格林威治时间转化
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            formatter.setTimeZone(TimeZone.getTimeZone("GMT 0"));
            String dateString = formatter.format(date.getTime());

            //签名字符串
            String credentialScope = dateString   "/"   Service   "/"   Stop;
            String hashedCanonicalRequest =   HashEncryption(CanonicalRequest);
            String stringToSign           =   Algorithm   "n"  
                    timestamp   "n"  
                    credentialScope   "n"  
                    hashedCanonicalRequest;

            //计算签名
            byte[] secretDate             =   HashHmacSha256Encryption(("TC3"   SecretKey).getBytes("UTF-8"), dateString);
            byte[] secretService          =   HashHmacSha256Encryption(secretDate, Service);
            byte[] secretSigning          =   HashHmacSha256Encryption(secretService, Stop);

            //签名字符串
            byte[] signatureHmacSHA256    =   HashHmacSha256Encryption(secretSigning, stringToSign);
            //替换java DatatypeConverter.printHexBinary(d).toLowerCase()

            StringBuilder builder = new StringBuilder();
            for (byte b : signatureHmacSHA256) {
                String hex = Integer.toHexString(b & 0xFF);
                if (hex.length() == 1) {
                    hex = '0'   hex;
                }
                builder.append(hex);
            }
            String signature = builder.toString().toLowerCase();
            //组装签名字符串
            String authorization          =   Algorithm   ' '  
                    "Credential="   SecretId   '/'   credentialScope   ", "  
                    "SignedHeaders="   SignedHeaders   ", "  
                    "Signature="   signature;

            //创建header 头部
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", authorization);
            headers.put("Host", "ocr.tencentcloudapi.com");
            headers.put("Content-Type", "application/json; charset=utf-8");
            headers.put("X-TC-Action", action);
            headers.put("X-TC-Version", version);
            headers.put("X-TC-Timestamp", timestamp);
            headers.put("X-TC-Region", region);

            //request 请求
            String response = requestPostData(Url, paramJson, headers);
            return response;
        }catch(Exception e){
            return e.getMessage();
        }
    }


    private static String  HashEncryption(String s)  throws Exception {
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        sha.update(s.getBytes());
        //替换java DatatypeConverter.printHexBinary(d).toLowerCase()
        StringBuilder builder = new StringBuilder();
        for (byte b : sha.digest()) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0'   hex;
            }
            builder.append(hex);
        }
        return builder.toString().toLowerCase();
    }

    private static byte[] HashHmacSha256Encryption(byte[] key, String msg) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, mac.getAlgorithm());
        mac.init(secretKeySpec);
        return mac.doFinal(msg.getBytes("UTF-8"));
    }


    /*
     * Function  :   发送Post请求到服务器
     * Param     :   params请求体内容,encode编码格式
     */
    public static String requestPostData(String strUrlPath, String data, Map<String, String> headers) {
        try {
            URL url = new URL(strUrlPath);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setConnectTimeout(3000);            //设置连接超时时间
            httpURLConnection.setDoInput(true);                  //打开输入流,以便从服务器获取数据
            httpURLConnection.setDoOutput(true);                 //打开输出流,以便向服务器提交数据
            httpURLConnection.setRequestMethod("POST");          //设置以Post方式提交数据
            httpURLConnection.setUseCaches(false);               //使用Post方式不能使用缓存
            //设置header
            if (headers.isEmpty()) {
                //设置请求体的类型是文本类型
                httpURLConnection.setRequestProperty("Content-Type", "application/json");
            } else {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    httpURLConnection.setRequestProperty(key, value);
                }
            }
            //设置请求体的长度
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length()));

            //获得输出流,向服务器写入数据
            if (data != null && !TextUtils.isEmpty(data)) {
                byte[] writebytes = data.getBytes();
                // 设置文件长度
                OutputStream outputStream = httpURLConnection.getOutputStream();
                outputStream.write(data.getBytes());
                outputStream.flush();
            }
            int response = httpURLConnection.getResponseCode();            //获得服务器的响应码
            if(response == HttpURLConnection.HTTP_OK) {
                InputStream inptStream = httpURLConnection.getInputStream();
                return dealResponseResult(inptStream);                     //处理服务器的响应结果
            }
        } catch (IOException e) {
            return "err: "   e.getMessage().toString();
        }
        return "-1";
    }

    /*
     * Function  :   封装请求体信息
     * Param     :   params请求体内容,encode编码格式
     */
    public static StringBuffer getRequestData(Map<String, String> params, String encode) {
        StringBuffer stringBuffer = new StringBuffer();        //存储封装好的请求体信息
        try {
            for(Map.Entry<String, String> entry : params.entrySet()) {
                stringBuffer.append(entry.getKey())
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(), encode))
                        .append("&");
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);    //删除最后的一个"&"
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuffer;
    }

    /*
     * Function  :   处理服务器的响应结果(将输入流转化成字符串)
     * Param     :   inputStream服务器的响应输入流
     */
    public static String dealResponseResult(InputStream inputStream) {
        String resultData = null;      //存储处理结果
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        try {
            while((len = inputStream.read(data)) != -1) {
                byteArrayOutputStream.write(data, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        resultData = new String(byteArrayOutputStream.toByteArray());
        return resultData;
    }
}

您觉得对你有帮助的话,记得给小编点个赞 !!!!!

0 人点赞