Java-开发中遇到的小tips

1,605 阅读3分钟

调用另一个服务的接口

想调用我nutrition_back服务的analysis接口,已经在这个服务上把analysis接口需要验证权限才能调用的这个设置取消,但是使用postman测试还是没法调用,后来发现是缺少了一个header参数。 Authorization: Bearer test

以下截图顺便记录一下怎么使用postman测试接口

Image.png

Image.png

Java中如何调用post接口并设置参数

参考了这个链接使用HttpClient。

String url = "http://127.0.0.1:8333/tlc/list";
String jsonParam = "{"condition":{"recipeAgencyID":"","recipeName":""+name+"","recipeTypeName":""},"+ ""pageParam":{"pageIndex": 1,"pageSize": 20}}";
String result = doPostJson(url,5000, jsonParam);

HttpClient使用示例(post、json、设置代理)_Muscleheng的博客-CSDN博客

IDEA如何添加依赖

image.png

点击添加后选择“from Maven”可以直接搜索下载,也可以自己下载好依赖包之后手动添加。

String操作

通过调用接口返回后得到了一个JSON字符串,怎么从中提取所需要的数据?

主要使用了indexOf(), subtring(), length(), contains()方法


public Recipe (String res, String id) {
//res的值类似:{"status":200,"success":true,"message":null,"result":{"data":[{"serialNo":3939,"id":"0207000000056","name":"山药木耳炒核桃","spell":"symecht","weightSoup":null,"weightNoSoup":null,"allWeightSoup":null,"allWeightNoSoup":null,"cookedWeight":140.0,"rawCooked":null,"frequencyFlag":null,"photo":null,"alias":"山药木耳炒核桃","cost":null,"price":null,"belongDepId":"7","descs":null,"cuisineFlag":"","foodFlag":"坚果类,薯类,深色蔬菜类","foodType":"","cookingMethods":"","mealFlag":"午餐,晚餐","dishFlag":"半荤","seasonFlag":"","suitableRiceFlag":"","textureFlag":"","flavorFlag":"","disieaseFlag":"","nutritionFlag":"","healthSceneFlag":"","sortPersonFlag":"","phiFlag":"","colourFlag":"","dishPrectice":null,"usageRateFlag":"","belongDepName":"东阳标准化菜肴库","composeList":[{"serialNo":5391,"recipeId":"0207000000056","foodName":"核桃(干,胡桃)","foodId":"0160000071004","weight":15.0,"netWeight":1.60000066E11},{"serialNo":5895,"recipeId":"0207000000056","foodName":"山药(鲜)(薯蓣,大薯)","foodId":"0160000047104","weight":110.0,"netWeight":1.60000049E11},{"serialNo":5896,"recipeId":"0207000000056","foodName":"木耳(水发,黑木耳,云耳)","foodId":"0160000051014","weight":15.0,"netWeight":1.60000049E11},{"serialNo":5897,"recipeId":"0207000000056","foodName":"精盐","foodId":"0160000207102","weight":0.5,"netWeight":1.60000213E11},{"serialNo":5898,"recipeId":"0207000000056","foodName":"葵花籽油","foodId":"0160000192009","weight":2.0,"netWeight":1.60000197E11}],"photos":[],"nutrientContent":{"energy":115.738,"protein":2.9207499536275865,"fat":6.0031999844759705,"carbohydrate":13.453149676322939,"vitA":0.9600749999999999,"na":215.28060035347937,"k":227.19150000000002,"mg":35.3495,"fe":1.2980500139594078,"vitB1":0.05682500103116036,"vitC":4.7795000000000005,"zn":0.46937501038610935,"ca":23.47,"dietaryFiber":1.7331499965786934,"vitB2":0.034789999742060894}}],"totalCount":1}}
    String sub = findIdSub(res, id);// 从一串食物中找到所要查找的那个
    energy = findNum(sub, "energy");// 找到这个食物营养分析中能量的数值
    ......
}

private String findIdSub (String res, String id) {
    int i = res.indexOf(id);
    if (i != -1) {
        return res.substring(i);
    } else {
        throw new IllegalArgumentException("Recipe-findIdSub-在返回结果中找不到这个ID的食物"+id);
    }
}

private float findNum(String res, String nutri) {
    int i = res.indexOf("""+nutri+""");
    int len = nutri.length();
    String n = "0";
    String n1 = "";
    float num = 0;
    if (i != -1) {
        n1 = res.substring(i + len + 3);
        int dot = n1.indexOf(',');
        n = n1.substring(0, dot);
        if (n.contains("}")) {
            n = n.substring(0, n.length() - 3);
        }
    }
    try {
        num = Float.parseFloat(n);
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("无法将这个字符串转成数字!"+n);
    }
    return num;
}

类型转换

String to Float

String str = "12";
float f = Float.parseFloat(str);