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.MorformedURLException,该异常本身是正确的,但该错误将密钥返回为xxxxxxxhttps。如何运行代码?
endpoint = "xxxxxxx";
URL url = new URL(endpoint+path);
您最终使用的URL是"xxxxxxxhttps://northeurope.api.cognitive.microsoft.com/text/analytics/v2.1/languages".
这不是一个有效的URL。