我试图将文件上传到服务器(不是我的)我想我确实做了它所需要的但如果我做错了请有人纠正我
这是API
POST https://i cant share the URL HTTP/1.1
Content-Type: multipart/form-data;
boundary=----------------------------8d19a412e59ea7e
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36
Content-Length: 567460
Expect: 100-continue
Connection: Keep-Alive
------------------------------8d19a412e59ea7e
Content-Disposition: form-data; name="filename"; filename="report.xml"
Content-Type: application/xml
我的要求
private String uploadFile(String sourceFile,url)
throws ClientProtocolException, IOException {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
HttpURLConnection conn;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "--------------------------8d19a412e59ea7e";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="
+ boundary);
conn.setRequestProperty("uploaded_file", "");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=fileName;fileName=" + sourceFile+ boundary);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
String serverResponseMessage = conn.getResponseMessage();
int responseCode = conn.getResponseCode();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String inputLine = null;
while ((inputLine = br.readLine()) != null)
System.out.println(inputLine);
return serverResponseMessage;
}