【发布时间】:2014-05-18 13:53:15
【问题描述】:
我正在尝试使用 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编码将JSON字符串转换成字节数组,然后直接写入到连接的输出流中。
-
代码中的另一个问题是您使用默认编码将 JSON 字符串转换为字节数组。然后,您使用数组的长度来设置内容长度。但是,您应用 DataOutputStream 以将字符串以 ASCII 模式写入(writeBytes 不使用编码;它会丢弃高位)。因此,您可能在宣布的内容长度和有效内容长度之间存在不匹配。
标签: java android httpurlconnection dataoutputstream