【发布时间】:2021-02-25 16:56:31
【问题描述】:
我正在尝试通过 API 使用 IBM 翻译器,它完全可以与 Postman 一起使用,并提供以下信息: enter image description here
我还添加了这样的用户通行证: enter image description here
现在我尝试在 java 中为相同的请求编写代码,但它不起作用并且总是失败,我正在阅读所有其他问题并回答并做了同样的事情但仍然无法正常工作! 这是我的代码:
private static void PostRequest() throws IOException {
URL url = new URL("https://api.eu-gb.language-translator.watson.cloud.ibm.com/instances/405430e3-281c-4c40-8d64-139173d288c3/v3/translate?version=2018-05-01");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
String username = "apikey";
String password = "xxxxxxxxxxxxxxx";
String authString = username + ":" + password;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
//create a request Body
String jsonBody = "{\"text\": [\"Hello, world.\", \"How are you?\"], \"model_id\":\"en-ar\"}";
//write it
try(OutputStream os = connection.getOutputStream()) {
byte[] input = jsonBody.getBytes("utf-8");
os.write(input, 0, input.length);
}catch (Exception e){
System.out.println(e.getCause());
}
//Read the response
try(BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
谁能告诉我我应该如何添加我的授权?
【问题讨论】:
标签: java api ibm-watson