我正在尝试通过HTTP从Eclipse-PlugIn Client上传文件。当我使用HTTPrequest的getOutputStream添加我的文件时,文本文件的连接失败,包括字符串“class”。如果文件中没有“class”,则连接正常。我
不知道为什么会这样。在服务器端,文件将被上传,链接缩短并可以打开。除了文本包含“类”之外,一切都正常应用。
答案 0 :(得分:0)
确保使用form-multipart encoded POST,如下例所示:
final String CHARSET = "ISO-8859-1";
final String CRLF = "\r\n";
String formFieldName = "uploadfile";
String fileName = "upload.jpeg";
String fileContentType = "image/jpeg";
URL url = new URL("http://localhost");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true); // if input is expected
String boundary = "--------------------"+System.currentTimeMillis();
StringBuilder postData = new StringBuilder();
postData.append("--").append(boundary).append(CRLF);
postData.append("Content-Disposition: form-data; name=\"").append(formFieldName).append("\"; filename=\"").append(fileName).append("\"").append(CRLF);
postData.append("Content-Type: ").append(fileContentType).append(CRLF);
postData.append(CRLF).append(new String(bytes, CHARSET)).append(CRLF);
postData.append("--").append(boundary).append("--").append(CRLF);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
connection.setRequestProperty("Content-Length", Integer.toString(postData.length()));
connection.setFixedLengthStreamingMode(postData.length());
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), CHARSET);
out.write(postData.toString());
out.close();
assert(connection.getResponseCode() == HttpURLConnection.HTTP_OK);
// if input is expected
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), CHARSET));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
干杯, 最大