我试图使用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();
...
}
答案 0 :(得分:9)
这是一个有以下变化的解决方案:
试一试:
// 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();
...
}
答案 1 :(得分:1)