【问题标题】:IBM Watson translator Post request, failed with Response 400IBM Watson 翻译器发布请求,响应 400 失败
【发布时间】: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


    【解决方案1】:

    我加班加点找到了答案,只好写如下代码:

    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());
    }
    

    回复是:

    {
    

    “翻译”:[{ “翻译”:“مرحبا أيها العالم” }, { “翻译”:“كيف حالك ؟” }], “字数”:8, “字符数”:25 }

    【讨论】:

      猜你喜欢
      • 2014-10-25
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 2021-11-21
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      相关资源
      最近更新 更多