Works once but when I tried again, I am now getting ERROR:500. What seems to be the problem? I’m using java with this code:
private String bitmapToBase64(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return Base64.getEncoder().encodeToString(byteArray);
}
return null;
}
private void sendRequestToAI(String requestBody) {
new Thread(() -> {
try {
URL url = new URL("https://api.openai.com/v1/chat/completions");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer " + "");
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(requestBody);
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Parse the JSON response
JSONObject jsonResponse = new JSONObject(response.toString());
JSONArray choices = jsonResponse.getJSONArray("choices");
if (choices.length() > 0) {
JSONObject content = choices.getJSONObject(0).getJSONObject("content");
String text = content.getString("text");
runOnUiThread(() -> {
Toast.makeText(SendImage.this, text, Toast.LENGTH_SHORT).show();
identifyplant.setText(text);
});
}
} else {
runOnUiThread(() -> {
Toast.makeText(SendImage.this, "Error: " + responseCode, Toast.LENGTH_SHORT).show();
});
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
runOnUiThread(() -> {
Toast.makeText(SendImage.this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
});
}
}).start();
}
Please help me fix. Thanks!