学习内容:学习JavaWeb(Day45)
1、有道翻译API使用json格式数据
2、JSONP
3、Ajax提交form表单
4、Web Uploader
1、有道翻译API使用json格式数据
(1)根据昨天学习的Ajax跨域操作,继续使用有道翻译API,用json数据格式传输数据。
使用的工具类不变
public class HttpReqUtil {
public static String getReq(String url) throws IOException {
//使用HttpClient发送get/post请求
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);//发送get请求,url是传输来的有道翻译API
CloseableHttpResponse response1 = httpclient.execute(httpGet);
System.out.println(response1);
try {
HttpEntity entity1 = response1.getEntity();
//getContent()方法获得entity1的内容并返回一个输入流,
//IOUtils类属于commons.io.jar包,IOUtils的toString方法将输入流转化为字符串
String result = IOUtils.toString(entity1.getContent(),"UTF-8");
return result;
} finally {
response1.close();
}
}
}
创建servlet
String q = request.getParameter("q");
//url编码格式中不允许出现空格,需要把空格替换为20%
q = q.replace(" ","%20");
//使用的有道翻译API的数据格式doctype=json
String result = HttpReqUtil.getReq("http://fanyi.youdao.com/openapi.do?keyfrom=neverland&key=969918857&type=data&doctype=json&version=1.1&q=" + q);
//设置contentType为application/json,传输之后进行json解析
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.print(result);
out.flush();
out.close();
创建jsp页面
<body>
请输入要翻译的内容:<input type="text" id="cont"> <input type="button" value="翻译" id="btn">
<div id="result"></div>
<script type="text/javascript">
$(function(){
$("#btn").click(function (){
//获取输入的内容
let cont = $("#cont").val();
//Ajax请求
$.getJSON("/transjson",{
q:cont},function (json){
//translation是一个json数据的键
let result = json.translation;
$