Dataoutputstream gives me a ‘Java io. IOException: unexpected end of stream ‘?
•
Java
I'm trying to use httpurlconnection to send a request from an Android application to WebService But sometimes it works, sometimes it doesn't work
When I try to send 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 have an "unexpected end of stream" exception in the dataoutputstream closing function
This 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(); ... }
Solution
Here are the solutions for the following changes:
It gets rid of dataoutputstream, which is of course the wrong use. > It sets and passes the content length correctly. > It does not rely on any default values for encoding, but explicitly sets UTF-8 in two places
Try:
// 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","application/json; charset=UTF-8"); OutputStream os = httpCon.getOutputStream(); os.write(bytes); os.close(); ... }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码