该方法需要的jar包 commons-codec-1.4.jar commons-httpclient-3.1.jar commons-logging-1.1.1.jar
以上各包 均可在apache上下载 或 用maven 下载
File f = new File("device1.png");
PostMethod filePost = new PostMethod(
"
Part[] parts = { new FilePart("filename", f) ,new StringPart("name1","value"),new StringPart("name2","value","")};
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);
}
--------------------------------------------分割线----------------------------------------------------------
上面的代码模拟的表单为
<form enctype="multipart/form-data" action=http://url/path method="POST">
<input type="file" name="filename"/>
<input type="text" name="name1"/>
<input type="text" name="name2"/>
<input type="submit"/>
</form>