/**
* Forms an HTTP request, sends it using GET method and returns the result
* of the request as a String.
*
* @param url
* The URL to query for a String response.
* @return The translated String.
* @throws Exception
* on error.
*/
private static String retrieveResponse(String url) throws Exception {
long ct = System.currentTimeMillis();
System.out.println("before==" + tokenExpiration);
System.out.println("######====" + (ct - tokenExpiration));
if (clientId != null && clientSecret != null && ct > tokenExpiration) {
// String tokenJson = getToken(clientId, clientSecret);
String tokenJson = httpPostGetToken();
System.out.println("tokenJson=========" + tokenJson);
JSONObject jsonObject = new JSONObject(tokenJson);
Integer expiresIn = jsonObject.getInt("expires_in");
tokenExpiration = System.currentTimeMillis()
+ ((expiresIn * 1000) - 1);// 10秒的生命周期,失效后,会再次获得AccessToken
token = "Bearer " + jsonObject.getString("access_token");
System.out.println("token==" + token);
System.out.println("after==" + tokenExpiration);
}
String to = "en";
String from = "zh-CHS";
url = url + "?text=" + URLEncoder.encode("你好", ENCODING) + "&from="
+ from + "&to=" + to + "&appId=" + token;
System.out.println("url=========" + url);
final HttpURLConnection uc = (HttpURLConnection) new URL(url)
.openConnection();
if (referrer != null)
uc.setRequestProperty("referer", referrer);
uc.setRequestProperty("Content-Type", contentType + "; charset="
+ ENCODING);
uc.setRequestProperty("Accept-Charset", ENCODING);
// if (token != null) {
// uc.setRequestProperty("Authorization", token);
// }
uc.setRequestMethod("GET");
uc.setDoOutput(true);
try {
final int responseCode = uc.getResponseCode();
final String result = inputStreamToString(uc.getInputStream());
if (responseCode != 200) {
throw new Exception("Error from Microsoft Translator API: "
+ result);
}
return result;
} finally {
if (uc != null) {
uc.disconnect();
}
}
}