我需要将文件以及其他字段发布到Webapi。这是我已经实现的代码,但它似乎没有工作。如何使用Java将文件与多个字段一起发布
FileInputStream fileStream = new FileInputStream(file);
b = new byte[(int)file.length()];
fileStream.read(b);
fileName = file.getName();
String crlf = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
URL url = new URL(URL);
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(twoHyphens+boundary+crlf);
wr.writeBytes("Content-Disposition: form-data; process=\"extractText\";user=\"" + username + "\";pass=\"" + password + "\";filename=\"" + file.getName() + "\";file=\"");
wr.write(b);
wr.writeBytes("\"" + crlf);
wr.writeBytes(crlf);
wr.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
wr.flush();
wr.close();
responseStream = new InputStreamReader(connection.getInputStream());
BufferedReader br = new BufferedReader(responseStream);
strBuff = new StringBuffer();
String s;
while ((s = br.readLine()) != null) {
strBuff.append(s);
}
br.close();
responseStream.close();
connection.disconnect();
str = strBuff.toString();
data = str;
parser = new JSONParser();
jsonObj = (JSONObject)parser.parse(str);
str = jsonObj.get("status").toString();
没有发布任何数据。请帮忙。
难道你平时有outputstreams包裹在try-catch代码? https://examples.javacodegeeks.com/core-java/io/dataoutputstream/write-string-as-bytes-to-file-with-dataoutputstream/ – cYrixmorten
是的,但我认为这是没有必要的,因为我没有发现任何异常。 –