IBM Watson 翻译器 Post 请求,失败,响应为 400

IBM Watson translator Post request, failed with Response 400

我正在尝试通过 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());
    }

谁能告诉我如何添加授权?

我工作更多并找到了答案,我不得不编写以下代码:

private static void PostRequest() throws IOException, InterruptedException {
  // Customer ID
    final String customerKey = username;
    // Customer secret
    final String customerSecret = password;

    // Concatenate customer key and customer secret and use base64 to encode the concatenated string
    String plainCredentials = customerKey + ":" + customerSecret;
    String base64Credentials = new String(Base64.encodeBase64(plainCredentials.getBytes()));
    // Create authorization header
    String authorizationHeader = "Basic " + base64Credentials;

    HttpClient client = HttpClient.newHttpClient();

    // Create HTTP request object
    HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url1))
            .POST(HttpRequest.BodyPublishers.ofString( "{\"text\": [\"Hello, world.\", \"How are you?\"], \"model_id\":\"en-ar\"}"))
            .header("Authorization", authorizationHeader)
            .header("Content-Type", "application/json")
            .build();
    // Send HTTP request
    HttpResponse<String> response = client.send(request,
            HttpResponse.BodyHandlers.ofString());

    System.out.println(response.body());
}

响应是:

{

“翻译”:[{ “翻译”:“你好世界” }, { “翻译”:“你好吗?” } ], word_count: 8, character_count: 25 }