使用DataOutputStream输出流的read方法出现读取字节不一致解决办法,本地和测试环境不一致

之前:

 DataInputStream in = new DataInputStream(connection.getInputStream());
   byte[] b = new byte[in.available()];
in.read(b);

之后:

private String getHttpURLConnection(String url1,String paream) throws IOException, JSONException
{
Long deviceId=1l;
URL url = new URL(url1);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
connection.setConnectTimeout(80*1000);
connection.setReadTimeout(80*1000);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeLong(deviceId);
//最短
JSONArray array = new JSONArray(paream);
out.writeShort(array.length());
for(int i=0;i<array.length();i++){
JSONObject obj = array.getJSONObject(i);
out.write(obj.getString("time").getBytes("UTF8"));
double d = obj.getDouble("lon");
int lon = (int)(d * 1000000);
out.writeInt(lon);
d = obj.getDouble("lat") ;
int lat = (int)(d * 1000000);
out.writeInt(lat);
out.writeFloat((float)obj.getDouble("speed"));
out.writeFloat((float)obj.getDouble("direc"));
}
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
StringBuilder sb=new StringBuilder();
String str;
while((str=br.readLine())!=null){
sb.append(str);
}
return sb.toString();
}

原文地址:https://www.cnblogs.com/liuying1995/p/5730469.html