附录4-Java调用示例

通过Java代码也可以快速接入先荐推荐系统。关键代码您可以直接从下文复制,也可以去GitHub上直接下载,链接如下:https://github.com/4paradigm-recom/recom-api-demo

1. 通过maven引入需要的lib

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.6</version>
</dependency>

2. HTTP通用调用类

package tools;


import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;


public class HttpTools {

    public static int HTTP_TIMEOUT_MS = 4000;

    public static String get(String url, int timeoutMs) {
        try {
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet get = new HttpGet(url);
            RequestConfig requestConfig =
                    RequestConfig.custom().setConnectionRequestTimeout(timeoutMs)
                            .setConnectTimeout(timeoutMs).setSocketTimeout(timeoutMs).build();
            get.setConfig(requestConfig);
            get.setHeader("Content-type", "application/json;charset=utf-8");
            HttpResponse response = client.execute(get);
            String result = EntityUtils.toString(response.getEntity());
            return result;
        } catch (Exception e) {
            System.out.println("postForResponse error, url:" + url + ", ex:" + e);
        }
        return "";
    }

    public static String post(String url, String jsonContent, int timeoutMs) {
        try {
            HttpClient client = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(url);
            RequestConfig requestConfig =
                    RequestConfig.custom().setConnectionRequestTimeout(timeoutMs)
                            .setConnectTimeout(timeoutMs).setSocketTimeout(timeoutMs).build();
            post.setConfig(requestConfig);
            post.setHeader("Content-type", "application/json;charset=utf-8");
            StringEntity se = new StringEntity(jsonContent, ContentType.APPLICATION_JSON);
            post.setEntity(se);
            HttpResponse response = client.execute(post);
            String result = EntityUtils.toString(response.getEntity());
            return result;
        } catch (Exception e) {
            System.out.println("postForResponse error, url:" + url + ", content:" + jsonContent + "ex:" + e);
        }
        return "";
    }
}

3. 调用示例

3.1 物料上传

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import tools.HttpTools;

public class MaterialService {
    // 物料的访问token,不同的accessToken对应不同的物料集
    private static String accessToken = "407265caafcb4c31bf9dbfb6b3b1ed32";
    private static String saveUrl = "https://nbrecsys.4paradigm.com/business/items?source=1&accessToken="+accessToken;
    // type表示查询类型 : 1-itemId;2-url
    private static String searchUrl = "https://nbrecsys.4paradigm.com/business/items/search?type=1&accessToken="+accessToken;
    // type表示删除类型 : 1-itemId;2-url
    private static String deleteUrl = "https://nbrecsys.4paradigm.com/business/items/remove?type=1&accessToken="+accessToken;

    public static void save(){
        // 做多一次可以上报100条
        JSONArray materials = new JSONArray();
        JSONObject material = new JSONObject();
        material.put("itemId", "1234567");//物料ID,物料唯一标识
        material.put("title", "测试物料");
        material.put("content", "物料内容");
        material.put("url", "http://www.material.com/1234567");//物料链接,物料库中唯一
        material.put("categoryId", "科技,计算机");
        material.put("publishTime", System.currentTimeMillis());//物料发布时间,毫秒级时间戳
        material.put("publisherId", "测试作者");
        material.put("isRecommend", 1);
        material.put("tag", "iOS,客户端");
        material.put("coverUrl", "http://www.coverUrl.com");//物料封面链接
        material.put("location", "用户地址");
        materials.add(material);

        System.out.println("物料上报内容:"+material.toJSONString());
        String result = HttpTools.post(saveUrl, materials.toJSONString(), HttpTools.HTTP_TIMEOUT_MS);
        System.out.println("返回结果为:"+result);
    }

    public static void search(){
        JSONArray itemIds = new JSONArray();
        itemIds.add("123456");
        itemIds.add("1234567");

        System.out.println("物料查询itemIds:"+itemIds.toJSONString());
        String result = HttpTools.post(searchUrl, itemIds.toJSONString(), HttpTools.HTTP_TIMEOUT_MS);
        System.out.println("返回结果为:"+result);
    }

    public static void delete(){
        JSONArray itemIds = new JSONArray();
        itemIds.add("123456");
        itemIds.add("1234567");

        System.out.println("物料查询itemIds:"+itemIds.toJSONString());
        String result = HttpTools.post(deleteUrl, itemIds.toJSONString(), HttpTools.HTTP_TIMEOUT_MS);
        System.out.println("返回结果为:"+result);
    }

    public static void main(String[] args) {
        save();
        search();
        delete();
    }
}

3.2 推荐服务请求

import com.alibaba.fastjson.JSONObject;

import tools.HttpTools;

public class RecallService {

    // requestID:请求id,随机的字符串
    // sceneID:场景ID
    // userId:用户ID,能标识用户的唯一值
    private static final String url = "https://nbrecsys.4paradigm.com/api/v0/recom/recall?requestID=wsctsemv48&sceneID=440&userID=ox1yfwmi55";

    public static void recall(){

        JSONObject postJson = new JSONObject();
        postJson.put("page", 0);
        // 相关推荐,需要提交一个物料的ID - itemID
        postJson.put("itemID", "27717ef240af3664ea3a879f17164f78");

        System.out.println("查询物料数据为:" + postJson.toJSONString());
        String result = HttpTools.post(url, postJson.toJSONString(), HttpTools.HTTP_TIMEOUT_MS);
        System.out.println("返回结果为:"+result);
    }

    public static void main(String[] args) {
        recall();
    }
}

3.3 用户行为上报

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import tools.HttpTools;

public class ActionLogService {

    // 商家的clientToken
    private static String clientToken = "730eb3d190664a34a2cb83172f52b729";
    private static String url = "https://nbrecsys.4paradigm.com/action/api/log?clientToken=" + clientToken;

    public static void log(){
        JSONObject json = new JSONObject();
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        json.put("date", time);

        JSONArray actions = new JSONArray();
        json.put("actions", actions);

        JSONObject action = new JSONObject();
        action.put("itemId", "123456");
        action.put("userId", "testUser");
        action.put("actionTime", System.currentTimeMillis());// 改行为触发时间,毫秒级时间戳
        action.put("requestId", "requestId");
        action.put("action", "show");// 行为事件:show\detailPageShow\collect\share\follow\like\dislike\duration       
        action.put("sceneId", 1);// 场景ID
        action.put("context", "I3WxRlJ4lbMLXZB7il18GRkqDfKdmQ1Xs1esaP8VbfMTk5GKscGAwYkxS277bjzADjEeWh8H");//推荐物料中,携带的context内容
        actions.add(action);

        System.out.println("日志上报内容为:" + json.toJSONString());
        String result = HttpTools.post(url, json.toJSONString(), HttpTools.HTTP_TIMEOUT_MS);
        System.out.println("返回结果为:"+result);
    }

    public static void main(String[] args) {
        log();
    }
}
Copyright ©2017 4Paradigm All Rights Reserved            文件修订时间: 2019-10-09 11:23:23

results matching ""

    No results matching ""