博客
关于我
百度接口根据关键字生成文章
阅读量:162 次
发布时间:2019-02-26

本文共 8010 字,大约阅读时间需要 26 分钟。

之前无意中被人说起百度可以根据关键字生成文章,感觉好厉害。于是就上手看看什么神奇。 

文章链接:

如果没有你想要的模块,可以选择自定义模块

  • API接口地址仅支持Get请求;
  • 接口返回结果要求UTF-8编码,为json串格式;

 参考:

没有数据源,于是,我就选择了天气这个模板。

根据创建应用, 

找到API Key,Secret Key

贴上我写的类

import java.util.HashMap;import java.util.Map;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.alibaba.fastjson.JSONObject;import com.example.demo.image.utils.AuthService;import com.example.demo.image.utils.HttpClientUtil;@RestControllerpublic class BaiduWenZhangController {				HttpClientUtil httpClientUtil=new HttpClientUtil();	/**	 * 百度接口https://aip.baidubce.com/rest/2.0/nlp/v1/gen_article	 * @throws Exception 	 */	@RequestMapping("/baiduTest")	public String test() throws Exception {		String  accesss_tokenStr=AuthService.getAuth();		String url="https://aip.baidubce.com/rest/2.0/nlp/v1/gen_article?access_token="+accesss_tokenStr;		String contentType="application/x-www-form-urlencoded";				/**		 * Body请求参数:		参数			是否必选	类型		描述		project_id	    是		int		项目ID,可在我的项目页面下“生成记录”内获取		数据源参数		     否		...		其他参数,即作为系统调用预置或用户提供的数据源的参数。UTF-8编码,没有参数可不传。		例如预置天气数据源,请求接口生成文章时传入的参数为:project_id=111&city=北京,就会返回北京的天气数据。		 */		Map
map =new HashMap
(); map.put("project_id", 8627); map.put("city", "北京"); // map.put("ganmao_desc", "我不会感冒"); // map.put("chuanyi_desc", "好想看娟娟穿裙子"); // map.put("yundong_desc", "可以骑车去,或者跑跑步"); String str=httpClientUtil.toBaidu(url,map,contentType); JSONObject jsonObject=JSONObject.parseObject(str); String wenzhang =jsonObject.getString("result"); return wenzhang; }}

 

public  String toBaidu(String url, Map
map,String contentType) throws Exception { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); String result=null; // 声明httpPost请求 HttpPost httpPost = new HttpPost(url); // 判断map不为空 if (map != null) { // 声明存放参数的List集合 List
params = new ArrayList
(); // 遍历map,设置参数到list中 for (Map.Entry
entry : map.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString())); } // 创建form表单对象 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8"); formEntity.setContentType(contentType); // 把表单对象设置到httpPost中 httpPost.setEntity(formEntity); } // 使用HttpClient发起请求,返回response CloseableHttpResponse response = httpClient.execute(httpPost); // 解析response封装返回对象httpResult // HttpTinyClient.HttpResult httpResult = null; if (response.getEntity() != null) { // httpResult = new HttpResult(response.getStatusLine().getStatusCode(), result= EntityUtils.toString(response.getEntity(), "UTF-8"); } else { // httpResult = new HttpResult(response.getStatusLine().getStatusCode(), ""); } // 返回结果 return result; }

 

import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.util.List;import java.util.Map;import com.alibaba.fastjson.JSONObject;/** * 获取token类 */public class AuthService {    /**     * 获取权限token     * @return 返回示例:     * {     * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",     * "expires_in": 2592000     * }     */    public static String getAuth() {        // 官网获取的 API Key 更新为你注册的        String clientId = "9W4i4HewHrIYyjzTmW3i9ZE*";        // 官网获取的 Secret Key 更新为你注册的        String clientSecret = "UsGi9EZKCBN4h0TcGM2iY460Wum3PQd*";        return getAuth(clientId, clientSecret);    }    /**     * 获取API访问token     * 该token有一定的有效期,需要自行管理,当失效时需重新获取.     * @param ak - 百度云官网获取的 API Key     * @param sk - 百度云官网获取的 Securet Key     * @return assess_token 示例:     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"     */    public static String getAuth(String ak, String sk) {        // 获取token地址        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";        String getAccessTokenUrl = authHost                // 1. grant_type为固定参数                + "grant_type=client_credentials"                // 2. 官网获取的 API Key                + "&client_id=" + ak                // 3. 官网获取的 Secret Key                + "&client_secret=" + sk;        try {            URL realUrl = new URL(getAccessTokenUrl);            // 打开和URL之间的连接            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();            connection.setRequestMethod("GET");            connection.connect();            // 获取所有响应头字段            Map
> map = connection.getHeaderFields(); // 遍历所有的响应头字段 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } // 定义 BufferedReader输入流来读取URL的响应 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String result = ""; String line; while ((line = in.readLine()) != null) { result += line; } /** * 返回结果示例 */ System.out.println("result:" + result); /** JSONObject jsonObject = new JSONObject(result); String access_token = jsonObject.getString("access_token"); return access_token; */ //我这里使用的是阿里的fastjson JSONObject jsonObject=JSONObject.parseObject(result); String access_token =jsonObject.getString("access_token"); return access_token; } catch (Exception e) { System.err.printf("获取token失败!"); e.printStackTrace(System.err); } return null; }}

 

 然后调用:   

 

返回说明

返回参数

参数 类型 描述
result array 成功时,返回的结果数组
+title string 文章标题
+summary string 文章摘要
+texts array 文章正文数组,每个数组元素代表一个段落,顺序为文章模板的段落顺序
error_code int 错误码,0代表成功,其他代表失败
error_msg string 错误信息,成功时为空,失败返回错误原因

返回示例

成功返回示例

{  "error_code": 0,    "error_msg": "",    "result": {        "texts": ["

今天的温度范围是-4 ~ 6℃。<\/p>", "

天气较好,但考虑天气寒冷,风力较强,推荐您进行室内运动,若户外运动请注意保暖并做好准备活动。<\/p>", "

各项气象条件适宜,无明显降温过程,发生感冒机率较低<\/p>"], "summary": "北京周四天气预报", "title": "

北京天气<\/p>" } }

失败返回示例

{    "error_code": 110,    "error_msg": "Access token invalid or no longer valid",    "result": []}

我返回来的是: 

{"error_code":0,"error_msg":"","result":{"texts":["

\u4eca\u5929\u5317\u4eac\u7684\u5929\u6c14\u6674\u70ed\u9ad8\u6e29\uff0c\u6700\u9ad8\u6c14\u6e2936\u2103\uff0c\u6700\u4f4e\u6c14\u6e2926\u2103\u3002\u5929\u6c14\u708e\u70ed\uff0c\u5efa\u8bae\u7740\u77ed\u886b\u3001\u77ed\u88d9\u3001\u77ed\u88e4\u3001\u8584\u578bT\u6064\u886b\u7b49\u6e05\u51c9\u590f\u5b63\u670d\u88c5\u3002\u672a\u6765\u51e0\u5929\uff0c\u6c14\u6e29\u4fdd\u6301\u5e73\u7a33\u3002<\/p>","

\u4eca\u5929\u7684\u751f\u6d3b\u6307\u5357\uff1a\u4eca\u5929\u5929\u6c14\u8f83\u597d\uff0c\u65e0\u96e8\u6c34\u56f0\u6270\uff0c\u4f46\u8003\u8651\u6c14\u6e29\u5f88\u9ad8\uff0c\u8bf7\u6ce8\u610f\u9002\u5f53\u51cf\u5c11\u8fd0\u52a8\u65f6\u95f4\u5e76\u964d\u4f4e\u8fd0\u52a8\u5f3a\u5ea6\uff0c\u8fd0\u52a8\u540e\u53ca\u65f6\u8865\u5145\u6c34\u5206\uff1b\u5065\u5eb7\u9632\u75c5\u65b9\u9762\uff0c\u5404\u9879\u6c14\u8c61\u6761\u4ef6\u9002\u5b9c\uff0c\u53d1\u751f\u611f\u5192\u673a\u7387\u8f83\u4f4e\u3002\u4f46\u8bf7\u907f\u514d\u957f\u671f\u5904\u4e8e\u7a7a\u8c03\u623f\u95f4\u4e2d\uff0c\u4ee5\u9632\u611f\u5192\uff1b\u5982\u679c\u60a8\u6709\u7231\u8f66\uff0c\u4eca\u5929\u6700\u8fd1\u4e09\u5929\u4f1a\u6709\u964d\u96e8\u3001\u5927\u98ce\u7b49\u6076\u52a3\u5929\u6c14\uff0c\u53ef\u80fd\u4f1a\u5bfc\u81f4\u60a8\u7684\u7231\u8f66\u518d\u6b21\u88ab\u5f04\u810f\uff0c\u5efa\u8bae\u4e0d\u8981\u9009\u62e9\u5728\u4eca\u5929\u6d17\u8f66\u200b\u3002<\/p>"],"summary":"

7\u670826\u65e5\uff0c\u5317\u4eac\u6674\u70ed\u9ad8\u6e29\u3002<\/p>","title":"

\u5317\u4eac\u5929\u6c14<\/p>"}}

 

返回到前端:

 

 

 在做修改

2019.10.23再次追加

可以用jsoup来解析。jsoup等用空了,我在做一篇文章讲解

 

 

 

控制应用: 

百度写作文档: 

转载地址:http://ndof.baihongyu.com/

你可能感兴趣的文章
MySQL8.0.29启动报错Different lower_case_table_names settings for server (‘0‘) and data dictionary (‘1‘)
查看>>
MYSQL8.0以上忘记root密码
查看>>
Mysql8.0以上重置初始密码的方法
查看>>
mysql8.0新特性-自增变量的持久化
查看>>
Mysql8.0注意url变更写法
查看>>
Mysql8.0的特性
查看>>
MySQL8修改密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
查看>>
MySQL8修改密码的方法
查看>>
Mysql8在Centos上安装后忘记root密码如何重新设置
查看>>
Mysql8在Windows上离线安装时忘记root密码
查看>>
MySQL8找不到my.ini配置文件以及报sql_mode=only_full_group_by解决方案
查看>>
mysql8的安装与卸载
查看>>
MySQL8,体验不一样的安装方式!
查看>>
MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
查看>>
Mysql: 对换(替换)两条记录的同一个字段值
查看>>
mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
查看>>
MYSQL:基础——3N范式的表结构设计
查看>>
MYSQL:基础——触发器
查看>>
Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
查看>>
mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
查看>>