如何使用Java将文件与多个字段一起发布

时间:2016-04-14 14:33:50

标签: java api post

我需要将文件与其他字段一起发布到服务器到webapi。这是我已经实施的代码,但它似乎无法正常工作。

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();

没有任何数据发布。请帮忙。

1 个答案:

答案 0 :(得分:0)

我建议使用Http客户端实现。

例如,这个显示如何使用Jersey客户端: https://stackoverflow.com/a/24647315/3356136

您还可以考虑其他实施,例如Apache HttpComponents