Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataOutputSteam is throwing me a 'java.io.IOException: unexpected end of stream'?

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();
    ...
}
like image 805
Laggel Avatar asked May 18 '14 13:05

Laggel


2 Answers

Here's a solution with the following changes:

  • It gets rid of the DataOutputStream, which is certainly the wrong thing to use.
  • It correctly sets and delivers the content length.
  • It doesn't depend on any defaults regarding the encoding, but explicitly sets UTF-8 in two places.

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();

    ...
}
like image 116
Codo Avatar answered Nov 03 '22 21:11

Codo


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.

like image 1
working Avatar answered Nov 03 '22 21:11

working