调用http接口ocr返回文本信息提取json字段写入txt

import json
import requests
import cv2 as cv
import os
import re
import random
import glob as gb
import time

'''
(1)json.dumps()函数是将一个Python数据类型列表进行json格式的编码(可以这么理解,json.dumps()函数是将字典转化为字符串)
(2)json.loads()函数是将json格式数据转换为字典(可以这么理解,json.loads()函数是将字符串转化为字典)
'''


def post_requests(url, data, file_path):
    files = {'file': open(str(file_path), 'rb')}

    angle_result = requests.post(url, files=files, data=data)
    # angle_result_utf = angle_result.content.decode('utf-8')
    angle_result_utf = angle_result.text
    # print(json.loads(angle_result_utf))
    # print(angle_result_utf)
    return json.loads(angle_result_utf)

def get_images(root):
    '''
    get images's path and name
    '''
    files = []
    for ext in ['jpg', 'png', 'jpeg', 'JPG']:
        files.extend(gb.glob(os.path.join(root, '*.{}'.format(ext))))
    name = []
    for i in range(len(files)):
        name.append(files[i].split('/')[-1])
    return files, name

def img_path_parse(data_path):
    # class_names = os.listdir(data_path)
    img_path = []
    class_dir_path = os.path.join(data_path)
    # c. 获取子文件夹中的所有图像名称
    image_names = os.listdir(class_dir_path)
    # d. 遍历所有图像,分别提取图像特征信息
    for image_name in image_names:
        # 1. 获取图像的具体路径
        image_path = os.path.join(class_dir_path, image_name)
        #image_name = image_name.split('.')[-2].split('/')[-1]
        # 2. 基于图像路径获取图像的特征数据,要求格式为: [features,]
        img_path.append(image_path)
    random.shuffle(img_path)
    return img_path

def readFilename(path, allfile):
    filelist = os.listdir(path)

    for filename in filelist:
        filepath = os.path.join(path, filename)
        if os.path.isdir(filepath):
            readFilename(filepath, allfile)
        else:
            allfile.append(filepath)
    return allfile


def imglist(path):
    img = []
    label = []
    for file in os.listdir(path):
        file_img = os.path.join(path, file)
        if os.path.isdir(file_img):
            img = img + os.listdir(file_img)
    num = len(img)
    for i in range(num):
        imgs = img[i]
        #name1 = imgs.split(".")[-2]  # 获取后缀之前的元素
        name1 = imgs.split('.')[-2].split('/')[-1]
        name2 = name1.split('%')[-1]  # 获取标签
        label = label + [int(name2)]
    assert len(img) == len(label)


    #print("train img:", len(img), "......train label", len(label))


if __name__ == '__main__':
    #img_path = "D:\\.....\\test1.jpg"
    #img_path = "E:\\trade\\贸易合同工期页\\"

    data_path = "E:\\trade\\贸易合同价款页"
    image_path = img_path_parse(data_path)
    #print(image_path)









    # for fname in os.listdir(img_path):
    #     if '.jpg' in fname or '.JPG' in fname or '.png' in fname:
    #         img_path = os.path.join(img_path, fname)


    for name in image_path:
        angle_result_utf = post_requests("http://172.16.:9009/icr/......", {}, name)
        #print(img_path)


        allfile1 = []
        allfile1 = readFilename(data_path, allfile1)
        allname1 = []

        # print(name)
        name = name
        t = name.split(".")[0].split("\\")[-1]

        t1 = allname1.append(t)

        #print(t)

        i = 0

        # file_handle = open('./{}.txt'.format(t), mode='a', encoding = 'utf-8')
        with open('E:/trade/gts/贸易合同价款页/{}.txt'.format(t), mode='a', encoding='utf-8') as f:
            for t in angle_result_utf["document"]["blocks"]:
                data = angle_result_utf["document"]["blocks"][i]["lines"][0]["text"]
                boxes = angle_result_utf["document"]["blocks"][i]["lines"][0]["position"]["vertices"]
                box2 = ", ".join(repr(e) for e in boxes)

                # print(box2)
                box2 = re.sub("\D", ' ', box2)
                box2 = ','.join(x for x in box2.split() if x)

                strl = box2 + ',' + data
                i = i + 1

                f.write(strl + '\n')
                # print(strl)
            # print(i)
            # f.close()



在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java调用HTTP接口传参JSON的步骤如下: 1. 创建一个HTTP连接对象,使用Java中的URL类来实现。 2. 设置HTTP请求方法为POST,使用URLConnection类的setRequestMethod()方法来实现。 3. 设置HTTP请求头,包括Content-Type和Accept等信息,使用URLConnection类的setRequestProperty()方法来实现。 4. 创建一个JSON对象,将需要传递的参数封装到JSON对象中。 5. 将JSON对象转换为字符串,使用JSON库中的toString()方法来实现。 6. 将字符串写入HTTP请求体中,使用URLConnection类的getOutputStream()方法来实现。 7. 发送HTTP请求,使用URLConnection类的connect()方法来实现。 8. 获取HTTP响应,使用URLConnection类的getInputStream()方法来实现。 9. 将HTTP响应转换为字符串,使用IO流读取HTTP响应体中的数据,并将其转换为字符串。 10. 解析HTTP响应,根据业务需求对HTTP响应进行解析和处理。 以上就是Java调用HTTP接口传参JSON的基本步骤。 ### 回答2: 对于需要调用 HTTP 接口传参 JSON 的 Java 开发者来说,可以使用 Java 提供的一些类库和框架来实现。 一种常用的方法是使用 Apache HttpClient 库来发送 HTTP 请求和接收 HTTP 响应。可以在项目中添加以下 Maven 依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> ``` 然后可以使用以下代码来实现 HTTP POST 请求,并传递 JSON 数据: ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.IOException; public class HttpClientDemo { public static void main(String[] args) throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost("http://example.com/api"); String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { HttpEntity responseEntity = response.getEntity(); System.out.println(responseEntity); } } } } ``` 在上面的代码中,首先创建了一个 HttpPost 对象,并指定了 API 的地址。然后定义了一个 JSON 字符串,作为请求的参数。接着使用 StringEntity 封装了 JSON 数据,设置了 ContentType 为 APPLICATION_JSON。最后通过 httpClient.execute() 方法发送 HTTP POST 请求并接收响应。 此外,还可以使用其他的 HTTP 客户端类库和框架,例如: - OkHttp - Spring WebClient - Jersey Client 以上都提供了方便的 API,可以方便地实现 HTTP 请求和响应的处理。 ### 回答3: Java可以通过HTTP请求来调用API接口,并且可以通过JSON格式来传递参数,实现前后端的数据交互。 1. Java的HTTP请求类 Java中常用的HTTP请求类有URLConnection和HttpClient,其中URLConnection是JDK自带的HTTP请求类,HttpClient则是一个第三方库,通过引入相关的jar包即可使用。 2. JSON格式的数据传递 在HTTP请求中,可以使用JSON的格式来传递数据,具体传递方法可以使用Java中的JSONObject类或者第三方库如GSON来实现。具体传递参数的方法可以参考以下示例代码: HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); //设置请求头 post.setHeader("Content-Type", "application/json"); //构建请求体 JSONObject jsonObj = new JSONObject(); jsonObj.put("param1", "value1"); jsonObj.put("param2", "value2"); StringEntity entity = new StringEntity(jsonObj.toString(), "UTF-8");//设置编码格式 post.setEntity(entity); HttpResponse response = client.execute(post);//发送请求 int statusCode = response.getStatusLine().getStatusCode();//获取响应码 if (statusCode == HttpStatus.SC_OK) { String result = EntityUtils.toString(response.getEntity());//获取响应结果 } 以上代码通过设置请求头("Content-Type", "application/json")来告诉服务器请求体是JSON格式的数据,然后通过JSONObject类构建请求体,并使用StringEntity将其转换为字符串格式,最后将请求体添加到HttpPost中即可。请求发送后,通过HttpResponse获取响应结果,并将响应结果转换为字符串格式。 总结 Java调用HTTP接口传参JSON的的方法有很多,可以使用Java自带的HTTP请求类URLConnection,也可以选择使用第三方库HttpClient等。而JSON格式的数据传递可以使用Java自带的JSONObject类或者第三方库如GSON进行处理。使用上述方法可以实现Java的HTTP请求和JSON格式数据传递,进行前后端数据交互。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值