gpt4 book ai didi

java - DataOutputStream 给我一个 'java.io.IOException: unexpected end of stream' ?

转载 作者:太空狗 更新时间:2023-10-29 22:57:25 26 4
gpt4 key购买 nike

我正在尝试使用 HttpUrlConnection 从 Android 应用程序向 Web 服务发出请求。但有时有效,有时无效。

当我尝试发送这个值时:

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", tokenType + " "+ accessToken);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

OutputStream os = httpCon.getOutputStream();
os.write(bytes);
os.close();

...
}

关于java - DataOutputStream 给我一个 'java.io.IOException: unexpected end of stream' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23722659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com