javaCopy code
import java.util.*;
import org.apache.http.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import org.apache.http.entity.*;
import com.fasterxml.jackson.databind.*;
public class ChatGPTClient {
private static final String API_URL = "https://api.openai.com/v1/engines/davinci-codex/completions";
private static final String API_KEY = "YOUR_OPENAI_API_KEY";
public String sendChatMessage(String message) throws Exception {
// create the HTTP client
CloseableHttpClient httpClient = HttpClients.createDefault();
// create the HTTP POST request
HttpPost httpPost = new HttpPost(API_URL);
httpPost.setHeader("Authorization", "Bearer " + API_KEY);
httpPost.setHeader("Content-Type", "application/json");
// create the request body
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("prompt", message);
requestBody.put("max_tokens", 60);
// convert the request body to JSON
String jsonRequestBody = new ObjectMapper().writeValueAsString(requestBody);
// set the request body to the HTTP POST request
httpPost.setEntity(new StringEntity(jsonRequestBody));
// execute the HTTP POST request
CloseableHttpResponse response = httpClient.execute(httpPost);
// get the response body
HttpEntity responseEntity = response.getEntity();
String jsonResponseBody = EntityUtils.toString(responseEntity);
// convert the response body from JSON
Map<String, Object> responseBody = new ObjectMapper().readValue(jsonResponseBody, Map.class);
// get the chat message from the response body
String chatMessage = (String) responseBody.get("choices").get(0).get("text");
// return theI'm sorry, the response was cut off accidentally. Here's the remaining part of the Java code:
```java
// return the chat message
return chatMessage;
}
}