DataOutputSteam给我一个’java.io.IOException:意外的流结束’?

前端之家收集整理的这篇文章主要介绍了DataOutputSteam给我一个’java.io.IOException:意外的流结束’?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用HttpUrlConnection从 Android应用程序发出请求到WebService.但有时候它有效,有时它不起作用.

当我尝试发送此值:

JSON值

{"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"}

我在DataOutputStream关闭函数中有一个“意外的流结束”异常.

这是我的代码

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

解决方法

以下是以下更改的解决方案:

它摆脱了DataOutputStream,这当然是错误的使用.
>它正确设置和传递内容长度.
>它不依赖于关于编码的任何默认值,而是在两个位置显式设置UTF-8.

尝试一下:

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

    ...
}
原文链接:https://www.f2er.com/java/126185.html

猜你在找的Java相关文章