public class AnalyticsDetectLanguage {
static String subscription_key_var;
static String subscription_key;
static String endpoint_var;
static String endpoint;
public static void Initialize () throws Exception {
subscription_key = "xxxxxx";
endpoint = "xxxxxxx";
}
static String path = "https://northeurope.api.cognitive.microsoft.com/text/analytics/v2.1/languages";
public static String GetLanguage (Documents documents) throws Exception {
String text = new Gson().toJson(documents);
byte[] encoded_text = text.getBytes("UTF-8");
URL url = new URL(endpoint+path);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/json");
connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscription_key);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(encoded_text, 0, encoded_text.length);
wr.flush();
wr.close();
StringBuilder response = new StringBuilder ();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
public static String prettify(String json_text) {
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(json_text).getAsJsonObject();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(json);
}
public static void main (String[] args) {
try {
Initialize();
Documents documents = new Documents ();
documents.add ("1", "This is a document written in English.");
documents.add ("2", "Este es un document escrito en Español.");
documents.add ("3", "这是一个用中文写的文件");
String response = GetLanguage (documents);
System.out.println (prettify (response));
}
catch (Exception e) {
System.out.println (e);
}
}
}
我正在尝试使用Microsoft Azure文本分析API,但是当我使用正确的密钥运行此代码时,在端点密钥本身上是正确的,但我得到了java.net.MalformedURLException,但错误将密钥返回为xxxxxxxhttps。如何使代码运行?
最佳答案
endpoint = "xxxxxxx";
URL url = new URL(endpoint+path);
最终得到的URL是“ xxxxxxxhttps://northeurope.api.cognitive.microsoft.com/text/analytics/v2.1/languages”。
无效的网址。