java google翻译api接口_使用httpclient实现免费的google翻译api

/**

* Copyright (c) Blackbear, Inc All Rights Reserved.

*/

package org.bb.util.net.http;

import java.io.BufferedInputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.util.Map;

import org.apache.commons.io.IOUtils;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.client.methods.HttpRequestBase;

import org.apache.http.conn.scheme.PlainSocketFactory;

import org.apache.http.conn.scheme.Scheme;

import org.apache.http.conn.scheme.SchemeRegistry;

import org.apache.http.conn.ssl.SSLSocketFactory;

import org.apache.http.entity.BufferedHttpEntity;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;

import org.apache.http.params.BasicHttpParams;

/**

* PostUtil.java

*

* @author catty

* @version 1.0, Created on 2008/2/20

*/

public class HttpClientUtil {

protected static Log log = LogFactory.getLog(HttpClientUtil.class);

protected static HttpClient httpclient = null;

protected static int maxTotal = 200;

protected static int maxPerRoute = 20;

protected static String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.77 Safari/535.7";

static {

if (httpclient == null) {

// ~~~~~~~~~~~~~~~~~~~~

// create httpclient

// ~~~~~~~~~~~~~~~~~~~~

SchemeRegistry reg = new SchemeRegistry();

reg.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

reg.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(reg);

cm.setMaxTotal(maxTotal);

cm.setDefaultMaxPerRoute(maxPerRoute);

httpclient = new DefaultHttpClient(cm);

}

}

/**

*

下載後回傳Inputstream

*

* @param url

* @return

* @throws Exception

*/

public static InputStream downloadAsStream(String url) throws Exception {

InputStream is = (InputStream) download(url, null, null, false);

return is;

}

/**

*

下載後儲存到File

*

* @param url

* @param saveFile

* @throws Exception

*/

public static void download(String url, File saveFile) throws Exception {

download(url, saveFile, null, false);

}

/**

*

下載

*

* @param url

* @param saveFile

* @param params

* @param isPost

* @return 如果saveFile==null則回傳inputstream, 否則回傳saveFile

* @throws Exception

*/

public static Object download(final String url, final File saveFile, final Map params,

final boolean isPost) throws Exception {

boolean saveToFile = saveFile != null;

// check dir exist ??

if (saveToFile && saveFile.getParentFile().exists() == false) {

saveFile.getParentFile().mkdirs();

}

Exception err = null;

HttpRequestBase request = null;

HttpResponse response = null;

HttpEntity entity = null;

FileOutputStream fos = null;

Object result = null;

try {

// create request

if (isPost) {

request = new HttpPost(url);

} else {

request = new HttpGet(url);

}

// add header & params

addHeaderAndParams(request, params);

// connect

response = httpclient.execute(request);

entity = response.getEntity();

entity = new BufferedHttpEntity(entity);

// get result

if (saveToFile) {// save to disk

fos = new FileOutputStream(saveFile);

IOUtils.copy(entity.getContent(), fos);

result = saveFile;

} else { // warp to inpustream

result = new BufferedInputStream(entity.getContent());

}

} catch (Exception e) {

err = e;

} finally {

// close

IOUtils.closeQuietly(fos);

// clear

request = null;

response = null;

entity = null;

if (err != null) {

throw err;

}

return result;

}

}

protected static void addHeaderAndParams(final HttpRequestBase request, final Map params) {

// add default header

request.addHeader("User-Agent", userAgent);

// add params

if (params != null) {

// map --> HttpParams

BasicHttpParams myParams = new BasicHttpParams();

for (String key : params.keySet()) {

myParams.setParameter(key, params.get(key));

}

request.setParams(myParams);

}

}

public static HttpClient getHttpclient() {

return httpclient;

}

public static void setHttpclient(HttpClient httpclient) {

HttpClientUtil.httpclient = httpclient;

}

public static int getMaxTotal() {

return maxTotal;

}

public static void setMaxTotal(int maxTotal) {

HttpClientUtil.maxTotal = maxTotal;

}

public static int getMaxPerRoute() {

return maxPerRoute;

}

public static void setMaxPerRoute(int maxPerRoute) {

HttpClientUtil.maxPerRoute = maxPerRoute;

}

public static String getUserAgent() {

return userAgent;

}

public static void setUserAgent(String userAgent) {

HttpClientUtil.userAgent = userAgent;

}

}

使用谷歌翻译 API 进行 Java 代码调用,你需要先获取到谷歌翻译 API 的访问凭证(API 密钥)。然后,你可以使用 HttpClient 或者其他网络请求库来发送 HTTP 请求并处理响应。下面是一个示例代码: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class GoogleTranslateAPI { public static void main(String[] args) { String apiKey = "YOUR_API_KEY"; String textToTranslate = "Hello, world!"; String sourceLanguage = "en"; String targetLanguage = "zh-CN"; try { String translation = translateText(apiKey, textToTranslate, sourceLanguage, targetLanguage); System.out.println("Translation: " + translation); } catch (IOException e) { e.printStackTrace(); } } public static String translateText(String apiKey, String text, String sourceLanguage, String targetLanguage) throws IOException { String encodedText = URLEncoder.encode(text, "UTF-8"); String urlStr = "https://translation.googleapis.com/language/translate/v2?key=" + apiKey + "&q=" + encodedText + "&source=" + sourceLanguage + "&target=" + targetLanguage; URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // Parse the JSON response to get the translated text String translatedText = parseTranslationResponse(response.toString()); return translatedText; } public static String parseTranslationResponse(String response) { // Parse the JSON response to extract the translated text // Implement your own logic here based on the response format return "Parsed translation"; } } ``` 请替换 `YOUR_API_KEY` 为你自己的谷歌翻译 API 密钥。以上代码中的 `translateText` 方法会发送 HTTP GET 请求到谷歌翻译 API,并解析返回的 JSON 响应以获取翻译结果。你可以根据需要自行解析 JSON 响应。 注意:以上代码只是一个简单示例,你可能需要根据实际需求进行修改和扩展。另外,为了保护 API 密钥,建议将其存储在安全的地方,不要直接在代码中硬编码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值