2016-04-14 20 views
0

我需要将文件以及其他字段发布到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(); 

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

+0

难道你平时有outputstreams包裹在try-catch代码? https://examples.javacodegeeks.com/core-java/io/dataoutputstream/write-string-as-bytes-to-file-with-dataoutputstream/ – cYrixmorten

+0

是的,但我认为这是没有必要的,因为我没有发现任何异常。 –

回答

0

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

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

你也可以考虑其他的实现比如Apache HttpComponents

+0

HttpClient与其他类一起被弃用。 –

+0

不赞成使用Commons HttpClient,Http Components取代它。 https://hc.apache.org/httpclient-legacy/index.html –

相关问题