I'm attempting to send an HTTP request from an AsyncTask in Android Studio, using the code below.
protected Long doInBackground(URL... urls) {
try {
HttpURLConnection connection = (HttpURLConnection) urls[0].openConnection();
connection.setRequestMethod("POST");
connection.connect();
byte[] loginRequestBytes = new Gson().toJson(loginRequest, LoginRequest.class).getBytes();
connection.getOutputStream().write(loginRequestBytes);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
ResponseBody responseBody = (ResponseBody) connection.getInputStream(); // ResponseBody extends InputStream
loginResponse = new Gson().fromJson(responseBody.toString(), LoginResponse.class);
}
} catch (IOException e) {
Log.e("HttpClient", e.getMessage(), e);
}
return null;
}
My ResponseBody class extends InputStream, so I thought that using
ResponseBody responseBody = (ResponseBody) connection.getInputStream();
would work, but here is the problem:
I'm getting a ClassCastException in my code, because connection.getInputStream() returns an object of type com.android.okhttp.okio.RealBufferedSource$1. Why is getInputStream not returning InputStream as per Java documentation? Is this an android-specific issue?
EDIT: I defined the ResponseBody class myself (shown below). It is not the one from okhttp, and it does extend InputStream, as far as I can tell.
public class ResponseBody extends InputStream {
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
String line;
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(this, "UTF-8"))) {
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
@Override
public int read() throws IOException {
return 0;
}
}