Home > Back-end >  How do I use LanguageTool API from Rapid API to check a string in Java?
How do I use LanguageTool API from Rapid API to check a string in Java?

Time:09-21

This is the code Rapid API created for me.

HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://dnaber-languagetool.p.rapidapi.com/v2/check"))
        .header("content-type", "application/x-www-form-urlencoded")
        .header("x-rapidapi-host", "dnaber-languagetool.p.rapidapi.com")
        .header("x-rapidapi-key", "[redacted to prevent abuse]")
        .method("POST", HttpRequest.BodyPublishers.ofString("text=This is a error.&language=en-US"))
        .build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());

This is what it outputs:

{"software":{"name":"LanguageTool","version":"5.5-SNAPSHOT","buildDate":"2021-09-17 18:41:41  0000","apiVersion":1,"premium":false,"premiumHint":"You might be missing errors only the Premium version can find. Contact us at support<at>languagetoolplus.com.","status":""},"warnings":{"incompleteResults":false},"language":{"name":"English (US)","code":"en-US","detectedLanguage":{"name":"English (US)","code":"en-US","confidence":0.528}},"matches":[{"message":"Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’.","shortMessage":"Wrong article","replacements":[{"value":"an"}],"offset":8,"length":1,"context":{"text":"This is a error.","offset":8,"length":1},"sentence":"This is a error.","type":{"typeName":"Other"},"rule":{"id":"EN_A_VS_AN","description":"Use of 'a' vs. 'an'","issueType":"misspelling","category":{"id":"MISC","name":"Miscellaneous"}},"ignoreForIncompleteSentence":false,"contextForSureMatch":1}]}

It seems to be working, but how do I make it so it checks my strings instead of the one they gave me?

Like if I had String myString = "Hello World. Hello World. Hello World." and I wanted to check this, where would I put the string in the code they provided to me?

I tried doing .method(myString) but it's not working.

Thanks in advance.

CodePudding user response:

You'd need to look at the API docs, but it seems you need to update the request body

I'm not familiar with this http client class, but either in the method

String x = "This is a error.";
... 
.method("POST", HttpRequest.BodyPublishers.ofString("text="   URLEncoder.encode(x, StandardCharsets.UTF_8.toString())  "&language=en-US")
.build();

Or the HttpResponse.BodyHandlers.ofString() needs to be given some similar input

  • Related