我想从我的Android应用程序发送文件中的一些数据,并将该文件保存在java Web服务器中 服务器页面永远不会收到任何数据,有人知道出了什么问题吗?
下面是我的客户端(android)和我的服务器(Java和Tomcat)。
客户端
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = "coleta.txt";
String urlServer = "http://192.168.2.219:8080/servidor_leite/produtores.jsp";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(getFileStreamPath(pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data;"
+ " name=\"uploadedfile\";filename=\""+ pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
Web服务器
ServletInputStream sis = request.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(sis));
String postData = new String();
while (in.ready()) {
postData += in.readLine();
}
try {
FileWriter fstream = new FileWriter(getServletContext()
.getRealPath("produtores.txt"));
PrintWriter writer = new PrintWriter(fstream);
writer.println("Bytes available '" + sis.available() + "'<br/>");
writer.println("in.ready() is '" + in.ready() + "'<br/>");
writer.println(postData);
// Close the output stream
writer.close();
}