我正在尝试使用Android将图像上传到Web服务器,以下代码在logcat中返回“E / Response:来自服务器的响应:null”。
protected String doInBackground(String... args) {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection connection = null;
String fileName = sourceFile.getName();
try {
connection = (HttpURLConnection) new URL(FILE_UPLOAD_URL).openConnection();
connection.setRequestMethod("POST");
String boundary = "---------------------------boundary";
String tail = "\r\n--" + boundary + "--\r\n";
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setDoOutput(true);
String metadataPart = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
+ "" + "\r\n";
String fileHeader1 = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"fileToUpload\"; filename=\""
+ fileName + "\"\r\n"
+ "Content-Type: application/octet-stream\r\n"
+ "Content-Transfer-Encoding: binary\r\n";
long fileLength = sourceFile.length() + tail.length();
String fileHeader2 = "Content-length: " + fileLength + "\r\n";
String fileHeader = fileHeader1 + fileHeader2 + "\r\n";
String stringData = metadataPart + fileHeader;
long requestLength = stringData.length() + fileLength;
connection.setRequestProperty("Content-length", "" + requestLength);
connection.setFixedLengthStreamingMode((int) requestLength);
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(stringData);
out.flush();
int progress = 0;
int bytesRead = 0;
byte buf[] = new byte[1024];
BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(sourceFile));
while ((bytesRead = bufInput.read(buf)) != -1) {
// write output
out.write(buf, 0, bytesRead);
out.flush();
progress += bytesRead; // Here progress is total uploaded bytes
publishProgress(""+(int)((progress*100)/totalSize)); // sending progress percent to publishProgress
}
// Write closing boundary and close stream
out.writeBytes(tail);
out.flush();
out.close();
// Get server response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder builder = new StringBuilder();
while((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
// Exception
} finally {
if (connection != null) connection.disconnect();
}
return null;
}
你知道我为什么会收到这个错误吗?