【问题标题】:Fetching GET request parameters from Java to Python Hug REST API从 Java 获取 GET 请求参数到 Python Hug REST API
【发布时间】:2019-02-02 19:15:32
【问题描述】:

我使用 Python Hug 创建了一个 Rest API,它接受一个列表作为参数。

Python REST API 代码

import hug
@hug.get('/myFunc/')
def myFunc(textList)
   print(len(textList))
   print(type(textList))

Java 代码

List<String> textArr = new ArrayList<String>(); 
File htmlsFolder =  new File(#html Folder Path);
try {
File[] files = htmlsFolder.listFiles();
for (File file : files) {    
html = new String(Files.readAllBytes(Paths.get(file.getPath())));
Document doc = Jsoup.parse(html); 
textArr.add(doc.body().text().replaceAll("[\\n\\t\\r\\s+]", " ")); 
}  
System.out.println(textArr.size());
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders(); 
HttpEntity<String> entity = new HttpEntity<String>(null, headers);
ResponseEntity<String> response = restTemplate.exchange("http://apiurl/myFunc?textList="+textArr.toString(), HttpMethod.GET, entity, String.class);

Java 代码从文件夹路径读取/解析 html 文件并将内容存储在 arrayList 中。如果有 17 个 html 文件,则 arrayList 的大小为 17。当调用 Python REST API 时,我在 python 端打印列表的长度,列表项的长度不一样,它在 500 左右。这是由于在 GET 请求中将参数作为查询字符串发送,还是 Java arrayList 和 Python List 之间存在转换问题?

System.out.println(textArr.size()); #gives 17(Java 代码)

print(len(textList)) #gives 543(Python 代码)

【问题讨论】:

    标签: java python rest api hug


    【解决方案1】:

    问题已得到解决,方法是将 api 作为 POST 方法,将 Java 中的值作为请求主体传递,并在 Python 端获取输入作为主体。

    import hug
    @hug.post('/myFunc/')
    def myFunc(body)
       textList = body['textList']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 1970-01-01
      • 2016-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多