您的位置:首页 > 其它

Ajax实现的bing 翻译接口 像词典一样

2012-12-02 00:00 351 查看
目的:用bing translator 实现像词典一样的查询

疑问:单词的翻译结果只有一个意思。本来是该有一组的.

扯:gooooal走了,只能用Bing 的,我是第一次写这个东西。菜鸟一个 ,请高人给指点!

在此,劳烦大家,希望给个解答!

================================================================================================

JSP页面:

<%@ page language="java" import="java.util.*,it.shopping.util.*" pageEncoding="UTF-8"%>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'testtranlation.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
function loadXMLDoc(){

xmlHttpRequest=null;
if (window.XMLHttpRequest)
{// code for IE7, Firefox, Opera, etc.

xmlHttpRequest=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE6, IE5
xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttpRequest!=null)
{
xmlHttpRequest.open("GET","AjaxSer",true);
xmlHttpRequest.onreadystatechange=state_Change;
xmlHttpRequest.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}

function state_Change()
{
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){

var responseText = xmlHttpRequest.responseText;
var from = "en", to = "Zh-CHS";
var word = document.getElementById("word").value;
var s = document.createElement("script");

s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate" +
"?appId=Bearer " + encodeURIComponent(responseText) +
"&from=" + encodeURIComponent(from) +
"&to=" + encodeURIComponent(to) +
"&text=" + encodeURIComponent(word) +
"&oncomplete=mycallback";
document.body.appendChild(s);
}
}

}

function mycallback(r){
document.getElementById("div2").innerHTML = r;
}

</script>

</head>

<body>
<input type="text" id="word"/>
<button type="button" onclick="loadXMLDoc()">translate</button><br>
<a id="div2" >hello</a>
</body>
</html>

AjaxSer.java(servlet):

package it.shopping.ser;

import it.shopping.util.TranlationApi;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AjaxSer extends HttpServlet {

/**
* Constructor of the object.
*/
public AjaxSer() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

System.out.println("11111");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
TranlationApi tranlationApi = new TranlationApi();
String accessToken = tranlationApi.getAccessToken();
out.print(accessToken);
out.flush();

}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

this.doGet(request,response);
}

public void init() throws ServletException {
// Put your code here
System.out.println("AjaxSer invoked");
}

}
java类: TranlationApi.java

package it.shopping.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class TranlationApi{

/*
* 通过调用getAccessToken
* @return String accesstoken
*/
public String getAccessToken()  {
String content = "grant_type=client_credentials";
content += "&client_id=71fac63a-8880-4bc4-ad25-78249513bb1c";
try {
content += "&client_secret=" + URLEncoder.encode("2T4jt96Y6Z+vNj77n6w2w2bXOIbXYT8IaR4gwWiElNk=","utf-8");
content += "&scope=http://api.microsofttranslator.com";
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

URL url = null;
URLConnection conn = null;
try {
url = new URL("https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/");

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conn = url.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Let the run-time system (RTS) know that we want input.
conn.setDoInput(true);
// Let the RTS know that we want to do output.
conn.setDoOutput(true);
// No caching, we want the real thing.
conn.setUseCaches(false);
// Specify the content type.
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

// Send POST output.
DataOutputStream printout = null;
try {
printout = new DataOutputStream(conn.getOutputStream());
printout.writeBytes(content);
printout.flush();
printout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// Get response data.
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str = "";
String str2 = " ";
int start2 = 0;
int end = 0;
int end2 = 0;
String accessToken = "";

try {
while (null != ( str = input.readLine())) {
end = str.indexOf(",") - 1;
str2 = str.substring(end + 16);
start2 = str2.indexOf(":")+ 2;
end2 = str2.indexOf(",") - 1;
accessToken = str2.substring(start2,end2);
System.out.println("access token: ");
System.out.println(accessToken);
}
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return accessToken;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: