java模拟form表单提交图片文件(转载)
这次要和别人开发的服务器端程序接口对接,之前实现的上传文件的方法对方接口无法接收。他们的接口需要类似这样的form提交数据:
<form enctype=”multipart/form-data” action=http://url/path method=”POST”>
<input name=”filename” type=”file” />
<input type=”submit” value=”test” />
</form>
解决办法是引入commons-httpclient.jar,下载地址http://hc.apache.org/downloads.cgi,模拟form表单提交数据,代码如下:
File f = new File(“device1.png”);
PostMethod filePost = new PostMethod( “http://url/path”);
Part[] parts = { new FilePart(“filename”, f)
};
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost .getParams()));
HttpClient clients = new HttpClient();
int status = clients.executeMethod(filePost);
try {
BufferedReader rd = new BufferedReader(new InputStreamReader( filePost.getResponseBodyAsStream(), “UTF-8”));
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
stringBuffer .append(line);
}
rd.close();
System.out.println(“接受到的流是:” + stringBuffer + “—-” + status);
} catch (Exception e) {
throw new RuntimeException(“error”,e);
}
解释一下
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost .getParams()));
设置多媒体参数,作用类似form表单中的enctype=”multipart/form-data” ,
Part[] parts = { new FilePart(“filename”, f) };
设定参数名称和值,类似form表单中的<input name=”filename” type=”file” />
try catch块主要是打印服务器端回传的数据。