java 请求 google translate

1 使用Java获取Google Translate结果

 

1.1 开发环境设置 Eclipse + Maven 插件

让 maven 顺便下载源码: Eclipse Preference->Maven->Download Artiface Sources 打勾

<dependencies>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency> <dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency> <dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency> <dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>
</dependencies>

1.2 使用 commons-httpclient-3.1 进行 https 请求

package com.zc.myhttps;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; public class MySSLSocketFactory implements ProtocolSocketFactory { private SSLContext sslcontext = null; private SSLContext createSSLContext() {
SSLContext sslcontext = null;
try {
sslcontext = SSLContext.getInstance("SSL");
sslcontext.init(null,
new TrustManager[] { new TrustAnyTrustManager() },
new java.security.SecureRandom()); } catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return sslcontext;
} private SSLContext getSSLContext() {
if (this.sslcontext == null) {
this.sslcontext = createSSLContext(); }
return this.sslcontext;
} public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(socket, host,
port, autoClose);
} public Socket createSocket(String host, int port) throws IOException,
UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(host, port);
} public Socket createSocket(String host, int port, InetAddress clientHost,
int clientPort) throws IOException, UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(host, port,
clientHost, clientPort);
} public Socket createSocket(String host, int port, InetAddress localAddress,
int localPort, HttpConnectionParams params) throws IOException,
UnknownHostException, ConnectTimeoutException {
if (params == null) {
throw new IllegalArgumentException("Parameters may not be null");
}
int timeout = params.getConnectionTimeout();
SocketFactory socketfactory = getSSLContext().getSocketFactory();
if (timeout == 0) {
return socketfactory.createSocket(host, port, localAddress,
localPort);
} else {
Socket socket = socketfactory.createSocket();
SocketAddress localaddr = new InetSocketAddress(localAddress,
localPort);
SocketAddress remoteaddr = new InetSocketAddress(host, port);
socket.bind(localaddr);
socket.connect(remoteaddr, timeout);
return socket;
}
} // 自定义私有类
private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
} public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
} public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
}
  • 再注册
Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
Protocol.registerProtocol("https", myhttps);
  • 最后就可以根据 httpclient 进行正常的 发送请求了:如 TestHttps.java
package com.zc.myhttps;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol; public class TestHttps {
public static String sendByGet(String url) {
HttpClient httpclient = null;
GetMethod method = null;
String result = ""; try {
httpclient = new HttpClient();
method = new GetMethod(url); httpclient.executeMethod(method);
BufferedReader bs = new BufferedReader(new InputStreamReader(
method.getResponseBodyAsStream(), "utf-8"));
String line = "";
while ((line = bs.readLine()) != null) {
result += line;
}
System.out.println("==========================获取到的结果");
System.out.println(result);
// System.out.println();
// System.out.println("HttpsUtil-sendByGet-url=" + url + "-result="
// + result);
} catch (Exception ex) {
ex.printStackTrace();
result = "error\tcrm error " + ex.toString();
System.out.println("HttpsUtil-sendByGet-url=" + url + "-result="
+ ex.toString()); } finally {
if (method != null) {
method.releaseConnection();
}
}
return result;
} public static String sendByPost(String url, Map param) {
HttpClient httpclient = null;
PostMethod method = null;
String result = ""; try { httpclient = new HttpClient();
method = new PostMethod(url);
if (param != null && !param.isEmpty()) {
int len = param.size();
method.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded;charset=utf-8");
NameValuePair[] np = new NameValuePair[len];
Iterator iter = param.keySet().iterator();
int i = 0;
while (iter.hasNext()) {
String k = (String) iter.next();
String v = (String) param.get(k);
np[i].setName(k);
np[i].setValue(v);
} method.setRequestBody(np);
} httpclient.executeMethod(method);
// result = method.getResponseBodyAsString();
BufferedReader bs = new BufferedReader(new InputStreamReader(
method.getResponseBodyAsStream(), "utf-8"));
String line = "";
while ((line = bs.readLine()) != null) {
result += line;
} System.out.println("HttpsUtil-sendByPost-url=" + url + "-result="
+ result); } catch (Exception ex) {
ex.printStackTrace();
result = "error\tcrm error " + ex.toString();
System.out.println("HttpsUtil-sendByPost-url=" + url + "-result="
+ ex.toString()); } finally {
if (method != null) {
method.releaseConnection();
}
} return result;
} public static void main(String[] args) {
Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
Protocol.registerProtocol("https", myhttps);
sendByGet("https://translate.google.com/#en/zh-CN/word");
}
}

1.3 进行处理具体的翻译请求

  • chrome 下通过调试工具找到具体的请求头,比如查询 "word",会发现如何请求 头:
https://translate.google.com/translate_a/single?client=t&sl=en&tl=zh-CN&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&source=bh&ssel=0&tsel=0&kc=1&tk=253493.388741&q=word

并且可以查看到响应的Response.

  • 分析Request,发现主要tk参数比如蛋疼,通过google搜索到一 个:https://github.com/cocoa520/Google_TK 感谢作者把这个tk参数搞出来.
  • 有了这个 tk 参数 ,然后加上上面的 Request,就可以很快的构造需要的 url.最后按照上面的httpclient就可以随意处理了.

1.4 使用命令行执行 xxx.class

  • 假如依赖 log4j json.jar

    java -cp /Users/mac/work/eclipse_luna/com.zc.myhttps/target/classes:/Users/mac/.m2/repository/org/json/json/20160212/json-20160212.jar:/Users/mac/.m2/repository/log4j/log4j/1.2.17/log4j-1.2.17.jar com.zc.myhttps.TestHttps
    

    注意:

    • -cp 相当于 -classpath
    • /Users/mac/work/eclipseluna/com.zc.myhttps/target/classes 这个路径加上 com.zc.myhttps.TestHttps 就可以找到 main 函数所在的文件.
    • -cp 后面依赖的jar包的分割符号是":"

Author: dai

Created: 2016-04-12 Tue 16:17

Emacs 24.5.1 (Org mode 8.2.10)

Validate

java 请求 google translate的更多相关文章

  1. Goslate: Free Google Translate API

    Python爬虫视频教程零基础小白到scrapy爬虫高手-轻松入门 https://item.taobao.com/item.htm?spm=a1z38n.10677092.0.0.482434a6E ...

  2. JMeter扩展Java请求实现WebRTC本地音视频推流压测脚本

    WebRTC是Web Real-Time Communication缩写,指网页即时通讯,是一个支持Web浏览器进行实时语音或视频对话的API,实现了基于网页的视频会议,比如声网的Agora Web ...

  3. 【JMeter】JMeter完成一个java请求的压测

    先定义一下我说的remoteService:即远程调用服务,没有http的url.不对外提供或者对外提供有限的服务.具体视各公司的代码架构所定,比如有些公司为web工程,scf服务,db.scf即为服 ...

  4. Jmeter性能测试之如何写Java请求测试用例类

    一. 引言: 最近工作中的一个项目要求做性能测试,该项目由提供服务的几个应用组成,选用的框架是阿里巴巴公司开源的服务框架Dubbo.关于Dubbo的介绍,网上也有很多资料,本人只是做了粗略的了解,没有 ...

  5. jmeter之自定义java请求性能测试

    一.环境准备         1.新建一个java工程         2.导入jar包:ApacheJMeter_core.jar     ApacheJMeter_java.jar         ...

  6. jmeter java请求

    demo下载地址http://yun.baidu.com/share/link?shareid=4277735898&uk=925574576 1.引用jmeter的jar包 到jmeter的 ...

  7. 转:JMeter进行Java 请求测试

    本文转自:http://blog.csdn.net/xiazdong/article/details/7873767 向原作者致敬,看了他的文章才让我顺利解决了JMeter测试中的问题,万分感谢! 目 ...

  8. 了解 : angular translate 和 google translate 和 微软 translate

    https://cloud.google.com/translate/v2/pricing google translate 一百万个字是$20,如果少过就得付$10,完全没有免费哦- 每天limit ...

  9. 第二篇--Jmeter测试Java请求

    前提:需要准备eclipse作为开发工具,安装jdk,准备完毕,接下来开工喽! 1.新建Java工程BMIrisJNIJarTest,新建lib目录,将Jmeter安装目录下lib/ext包下的Apa ...

随机推荐

  1. 22. javacript高级程序设计-高级技巧

    1. 高级技巧 1.1 函数 l 可以使用惰性载入函数,将任何分支推迟到第一个调用函数的时候 l 函数绑定可以让你创建始终在指定环境中运行的函数,同时函数柯里化可以让你创建已经填写了某些参数的函数 l ...

  2. Mac系统搭建java开发环境

    今天尝试在mac下搭建java开发环境 包括 JDK,Tomcat , eclipse ,mysql ,mysqlGUI

  3. 【python】入门学习(一)

    主要记录一下与C语言不同的地方和特别需要注意的地方: // 整除 ** 乘方 整数没有长度限制,浮点数有长度限制 复数: >>> 1j*1j (-1+0j) 导入模块: import ...

  4. c#指定日期格式

    string TripCode = "BT"+DateTime.Now.ToString("yyyyMMddHHmmss");//出差单号

  5. html与js传json值给php

    //一段js代码 var data = {}, act = [], list = []; $('.set').find('input, textarea').each(function() { act ...

  6. log4j介绍以及使用教程

    一.介绍 Log4j是Apache的一个开放源代码项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台.文件.GUI组件.甚至是套接 口服务 器.NT的事件记录器.UNIX Syslog ...

  7. iOS计算字符串的宽度高度

    OC开发中会遇到根据字符串和字体大小来算计算出字符串所占的宽高->> 封装方法如下: #import <Foundation/Foundation.h> #import < ...

  8. instanceof、 isinstance 与 isAssignableFrom的区别

    instanceof运算符 只被用于对象引用变量,检查左边的被测试对象 是不是 右边类或接口的 实例化.如果被测对象是null值,则测试结果总是false. 形象地:自身实例或子类实例 instanc ...

  9. Android高性能ORM数据库DBFlow入门

    DBFlow,综合了 ActiveAndroid, Schematic, Ollie,Sprinkles 等库的优点.同时不是基于反射,所以性能也是非常高,效率紧跟greenDAO其后.基于注解,使用 ...

  10. GB2312、GBK和UTF-8三种编码以及QT中文显示乱码问题

    1.GB2312.GBK和UTF-8三种编码的简要说明 GB2312.GBK和UTF-8都是一种字符编码,除此之外,还有好多字符编码.只是对于我们中国人的应用来说,用这三种编码 比较多.简单的说一下, ...