百度接口根据关键字生成文章
之前无意中被人说起百度可以根据关键字生成文章,感觉好厉害。于是就上手看看什么神奇。
文章链接:https://ai.baidu.com/docs#/IntelligentWriting-API/2843fe5c
如果没有你想要的模块,可以选择自定义模块
API接口地址仅支持Get请求;接口返回结果要求UTF-8编码,为json串格式;参考:https://ai.baidu.com/docs#/IntelligentWriting_intro/a79d81a7
没有数据源,于是,我就选择了天气这个模板。
根据创建应用,
找到APIKey,SecretKey
贴上我写的类
importjava.util.HashMap;importjava.util.Map;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importcom.alibaba.fastjson.JSONObject;importcom.example.demo.image.utils.AuthService;importcom.example.demo.image.utils.HttpClientUtil;@RestControllerpublicclassBaiduWenZhangController{HttpClientUtilhttpClientUtil=newHttpClientUtil();/***百度接口https://aip.baidubce.com/rest/2.0/nlp/v1/gen_article*@throwsException*/@RequestMapping("/baiduTest")publicStringtest()throwsException{Stringaccesss_tokenStr=AuthService.getAuth();Stringurl="https://aip.baidubce.com/rest/2.0/nlp/v1/gen_article?access_token="+accesss_tokenStr;StringcontentType="application/x-www-form-urlencoded";/***Body请求参数:参数是否必选类型描述project_id是int项目ID,可在我的项目页面下“生成记录”内获取数据源参数否...其他参数,即作为系统调用预置或用户提供的数据源的参数。UTF-8编码,没有参数可不传。例如预置天气数据源,请求接口生成文章时传入的参数为:project_id=111&city=北京,就会返回北京的天气数据。*/Mapmap=newHashMap();map.put("project_id",8627);map.put("city","北京");//map.put("ganmao_desc","我不会感冒");//map.put("chuanyi_desc","好想看娟娟穿裙子");//map.put("yundong_desc","可以骑车去,或者跑跑步");Stringstr=httpClientUtil.toBaidu(url,map,contentType);JSONObjectjsonObject=JSONObject.parseObject(str);Stringwenzhang=jsonObject.getString("result");returnwenzhang;}}publicStringtoBaidu(Stringurl,Mapmap,StringcontentType)throwsException{CloseableHttpClienthttpClient=HttpClientBuilder.create().build();Stringresult=null;//声明httpPost请求HttpPosthttpPost=newHttpPost(url);//判断map不为空if(map!=null){//声明存放参数的List集合Listparams=newArrayList();//遍历map,设置参数到list中for(Map.Entryentry:map.entrySet()){params.add(newBasicNameValuePair(entry.getKey(),entry.getValue().toString()));}//创建form表单对象UrlEncodedFormEntityformEntity=newUrlEncodedFormEntity(params,"utf-8");formEntity.setContentType(contentType);//把表单对象设置到httpPost中httpPost.setEntity(formEntity);}//使用HttpClient发起请求,返回responseCloseableHttpResponseresponse=httpClient.execute(httpPost);//解析response封装返回对象httpResult//HttpTinyClient.HttpResulthttpResult=null;if(response.getEntity()!=null){//httpResult=newHttpResult(response.getStatusLine().getStatusCode(),result=EntityUtils.toString(response.getEntity(),"UTF-8");}else{//httpResult=newHttpResult(response.getStatusLine().getStatusCode(),"");}//返回结果returnresult;}
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.net.URL;importjava.util.List;importjava.util.Map;importcom.alibaba.fastjson.JSONObject;/***获取token类*/publicclassAuthService{/***获取权限token*@return返回示例:*{*"access_token":"24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",*"expires_in":2592000*}*/publicstaticStringgetAuth(){//官网获取的APIKey更新为你注册的StringclientId="9W4i4HewHrIYyjzTmW3i9ZE*";//官网获取的SecretKey更新为你注册的StringclientSecret="UsGi9EZKCBN4h0TcGM2iY460Wum3PQd*";returngetAuth(clientId,clientSecret);}/***获取API访问token*该token有一定的有效期,需要自行管理,当失效时需重新获取.*@paramak-百度云官网获取的APIKey*@paramsk-百度云官网获取的SecuretKey*@returnassess_token示例:*"24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"*/publicstaticStringgetAuth(Stringak,Stringsk){//获取token地址StringauthHost="https://aip.baidubce.com/oauth/2.0/token?";StringgetAccessTokenUrl=authHost//1.grant_type为固定参数+"grant_type=client_credentials"//2.官网获取的APIKey+"&client_id="+ak//3.官网获取的SecretKey+"&client_secret="+sk;try{URLrealUrl=newURL(getAccessTokenUrl);//打开和URL之间的连接HttpURLConnectionconnection=(HttpURLConnection)realUrl.openConnection();connection.setRequestMethod("GET");connection.connect();//获取所有响应头字段Mapmap=connection.getHeaderFields();//遍历所有的响应头字段for(Stringkey:map.keySet()){System.out.println(key+"--->"+map.get(key));}//定义BufferedReader输入流来读取URL的响应BufferedReaderin=newBufferedReader(newInputStreamReader(connection.getInputStream()));Stringresult="";Stringline;while((line=in.readLine())!=null){result+=line;}/***返回结果示例*/System.out.println("result:"+result);/**JSONObjectjsonObject=newJSONObject(result);Stringaccess_token=jsonObject.getString("access_token");returnaccess_token;*///我这里使用的是阿里的fastjsonJSONObjectjsonObject=JSONObject.parseObject(result);Stringaccess_token=jsonObject.getString("access_token");returnaccess_token;}catch(Exceptione){System.err.printf("获取token失败!");e.printStackTrace(System.err);}returnnull;}}
然后调用: http://127.0.0.1:8080/baiduTest
返回说明
返回参数
参数类型描述resultarray成功时,返回的结果数组+titlestring文章标题+summarystring文章摘要+textsarray文章正文数组,每个数组元素代表一个段落,顺序为文章模板的段落顺序error_codeint错误码,0代表成功,其他代表失败error_msgstring错误信息,成功时为空,失败返回错误原因返回示例成功返回示例
{"error_code":0,"error_msg":"","result":{"texts":["今天的温度范围是-4~6℃。","
天气较好,但考虑天气寒冷,风力较强,推荐您进行室内运动,若户外运动请注意保暖并做好准备活动。","
各项气象条件适宜,无明显降温过程,发生感冒机率较低"],"summary":"北京周四天气预报","title":"
北京天气"}}
失败返回示例
{"error_code":110,"error_msg":"Accesstokeninvalidornolongervalid","result":[]}我返回来的是:
{"error_code":0,"error_msg":"","result":{"texts":["u4ecau5929u5317u4eacu7684u5929u6c14u6674u70edu9ad8u6e29uff0cu6700u9ad8u6c14u6e2936u2103uff0cu6700u4f4eu6c14u6e2926u2103u3002u5929u6c14u708eu70eduff0cu5efau8baeu7740u77edu886bu3001u77edu88d9u3001u77edu88e4u3001u8584u578bTu6064u886bu7b49u6e05u51c9u590fu5b63u670du88c5u3002u672au6765u51e0u5929uff0cu6c14u6e29u4fddu6301u5e73u7a33u3002","
u4ecau5929u7684u751fu6d3bu6307u5357uff1au4ecau5929u5929u6c14u8f83u597duff0cu65e0u96e8u6c34u56f0u6270uff0cu4f46u8003u8651u6c14u6e29u5f88u9ad8uff0cu8bf7u6ce8u610fu9002u5f53u51cfu5c11u8fd0u52a8u65f6u95f4u5e76u964du4f4eu8fd0u52a8u5f3au5ea6uff0cu8fd0u52a8u540eu53cau65f6u8865u5145u6c34u5206uff1bu5065u5eb7u9632u75c5u65b9u9762uff0cu5404u9879u6c14u8c61u6761u4ef6u9002u5b9cuff0cu53d1u751fu611fu5192u673au7387u8f83u4f4eu3002u4f46u8bf7u907fu514du957fu671fu5904u4e8eu7a7au8c03u623fu95f4u4e2duff0cu4ee5u9632u611fu5192uff1bu5982u679cu60a8u6709u7231u8f66uff0cu4ecau5929u6700u8fd1u4e09u5929u4f1au6709u964du96e8u3001u5927u98ceu7b49u6076u52a3u5929u6c14uff0cu53efu80fdu4f1au5bfcu81f4u60a8u7684u7231u8f66u518du6b21u88abu5f04u810fuff0cu5efau8baeu4e0du8981u9009u62e9u5728u4ecau5929u6d17u8f66u200bu3002"],"summary":"
7u670826u65e5uff0cu5317u4eacu6674u70edu9ad8u6e29u3002","title":"
u5317u4eacu5929u6c14"}}
返回到前端:
在做修改
2019.10.23再次追加
可以用jsoup来解析。jsoup等用空了,我在做一篇文章讲解
控制应用: https://console.bce.baidu.com/ai/#/ai/intelligentwriting/overview/index
百度写作文档: https://ai.baidu.com/docs#/IntelligentWriting-API/2843fe5c