I'm trying to make a Request to a WebService from an android application, using HttpUrlConnection. But sometimes it works, and sometimes it does not.
When I try sending this value:
JSON value
{"Calle":"Calle Pérez 105","DetalleDireccion":"","HoraPartida":"May 18, 2014 9:17:10 AM","Numero":0,"PuntoPartidaLat":18.477295994621315,"PuntoPartidaLon":-69.93638522922993,"Sector":"Main Sector"}
I got an "unexpected end of stream" Exception in the DataOutputStream close function.
Here is my code:
DataOutputStream printout;
// String json;
byte[] bytes;
DataInputStream input;
URL serverUrl = null;
try {
serverUrl = new URL(Config.APP_SERVER_URL + URL);
} catch (MalformedURLException e) {
...
}
bytes = json.getBytes();
try {
httpCon = (HttpURLConnection) serverUrl.openConnection();
httpCon.setDoOutput(true);
httpCon.setUseCaches(false);
httpCon.setFixedLengthStreamingMode(bytes.length);
httpCon.setRequestProperty("Authorization", tokenType + " "+ accessToken);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type", "application/json");
printout = new DataOutputStream(httpCon.getOutputStream());
printout.writeBytes(json);
printout.flush();
printout.close();
...
}
Here's a solution with the following changes:
Try it:
// String json;
URL serverUrl = null;
try {
serverUrl = new URL(Config.APP_SERVER_URL + URL);
} catch (MalformedURLException e) {
...
}
try {
byte[] bytes = json.getBytes("UTF-8");
httpCon = (HttpURLConnection) serverUrl.openConnection();
httpCon.setDoOutput(true);
httpCon.setUseCaches(false);
httpCon.setFixedLengthStreamingMode(bytes.length);
httpCon.setRequestProperty("Authorization", tokenType + " "+ accessToken);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStream os = httpCon.getOutputStream();
os.write(bytes);
os.close();
...
}
From the oracle documentation here. We know that flush method of DataOutputStream calls the flush method of the underlying output stream. If you look at the URLConnection class in here it says that every subclass of URLConnection must have this method overridden. If you see the HttpUrlConnection here we see that flush method is not overridden. It could be one of the reasons for your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With